ArticleDirectory
- 1. While Loop
- II. For Loop
- Iii. If statement
- Iv. Range statement
- 5. Else statements
- A practical example
The fastest way to get started is to write your ownProgram, This chapter mainly starts from the actual example
1. While Loop
#! /Usr/bin/Python # Fibonacci series: a, B = 0, 1 while B <100: Print B a, B = B, A + B
In this example, we can see severalC LanguageDifferent Places:
1) multiple values (multiple assignment), a, B = 0, and 1 are supported, so that the new values 0 and 1 are set at the same time.
2) The loop subject does not have a C language like {}, but is switched to indentation for control.
3) the judgment statement must be followed by a colon (:), which is used to the C program and needs to be adapted.
II. For Loop
A = ['cat', 'Dog', 'pig'] for X in a print x
Iii. If statement
If x <0: x = 0; Elif x = 0: x = 1
Iv. Range statement
In python, range actually generates a column (list), range (5), the generated list is [0, 1, 2, 3, 4], range (5, 10 ), the generated list is [5, 6, 7, 8, 9].
5. Else statements
The Python loop has an else clause. The program after this clauseCodeIt will be executed when the entire loop ends normally. (For a for loop, it indicates that the list has been reached, and for a while loop, it indicates that the conditional is changed to false ). However, if the program code of the else clause ends abnormally (due to the break description), it will not be executed.
A practical example
Find all prime numbers within 100:
For N in range (2,100): for I in range (2, n): If n % I = 0: Break else: Print N, 'is a prime number'
You can run it.