1 While循环:
语法:
while expression:
statement(s)
单语句的while循环:
while expression : statement
2 For循环:
语法:
for iterating_var in sequence:
statements(s)
If a sequence contains an expression list, it is evaluated first. Then,
the first item in the sequence is assigned to the iterating variable iterating_var
. Next, the statements block is executed. Each item in the list is assigned to iterating_var
, and the statements(s) block is executed until the entire sequence is exhausted.
example:
#!/usr/bin/python
for letter in 'Python': # First Example
print ('Current Letter :', letter)
fruits = ['banana', 'apple', 'mango']
for fruit in fruits: # Second Example
print ('Current fruit :', fruit)
print ("Good bye!")
output:D
:/>python test.py
Current Letter : P
Current Letter : y
Current Letter : t
Current Letter : h
Current Letter : o
Current Letter : n
Current fruit : banana
Current fruit : apple
Current fruit : mango
Good bye!
An alternative way of iterating through each item is by index offset into the sequence itself:
#!/usr/bin/python
fruits = ['banana', 'apple', 'mango']
for index in range(len(fruits)):
print 'Current fruit :', fruits[index]
print "Good bye!"
3 退出循环:
Break 退出整个循环;
continue退出本次循环,继续下次循环。
4The else
Statement Used with Loops
Python supports to have an else statement associated with a loop statements.
If the else statement is used with a for loop, the else statement is executed when the loop has exhausted iterating the list.
If the else statement is used with a while loop, the else statement is executed when the condition becomes false.
The following example illustrates the combination of an else statement with a for statement that searches for prime numbers from 10 through 20.
#!/usr/bin/python |
This will produce following result:
10 equals 2 * 5 |
Similar way you can use else statement with while loop.
The pass statement in Python is used when a statement is required syntactically but you do not want any command or code to execute.
The pass statement is a null operation; nothing happens when it executes. The pass is also useful in places where your code will eventually go, but has not been written yet (e.g., in stubs for example):
#!/usr/bin/python |
This will produce following result:
Current Letter : P |
The preceding code does not execute any statement or code if the value of letter is 'h'. The pass statement is helpful when you have created a code block but it is no longer required.
You can then remove the statements inside the block but let the block remain with a pass statement so that it doesn't interfere with other parts of the code.
python支持连续比较 如a<b<c 他等同于a<b b<c