The process control loop Python --while
First, grammar
while 条件:
执行代码
while
Meaning that when it refers to as its rear condition is satisfied, executes while
the following code.
Example: from 0 to write a print program 10
count = 0
while count <= 10:
print('第%s次' % count)
count += 1
If you want to print between 1 to 10 how to do it an even number?
They would have to find out, how to determine whether a number is even? Divisible by 2 is an even number, but how to determine whether the number divisible by 2 it? Simple, direct determination after this number is divided by 2 is 0 or not on the line, which uses the modulo operator described previously, "the operator of the Python" in the %
.
count = 1
while count <= 10:
if count % 2 == 0:
print('偶数:%s' % count)
count += 1
Second, the cycle is aborted statement
1, the cycle of death
There is a cycle called an infinite loop, as long as a trigger, you run to the highest power, machine fever paralysis.
As long as the conditions have been established while back that is has been true (True) will have been implemented, such as:
count = 0
while True: # 布尔值中的True本身就是真
print('不会结束的,打不完的!')
count += 1 # count怎么加都没用,因为while后面的判断语句与count无关
2、break
break for a complete end loop out of the loop body, the rear body of the code execution cycle
count = 0
while count <= 10:
print('第%s次' % count)
if count == 5: # 当count等于5时,执行break
break
count += 1
print('循环结束!') # 注意缩进!此代码不在循环体内。
3、continue
continue and break somewhat similar, except that only continue to terminate the present cycle, will be followed later execution cycle , break the cycle is completely terminated.
count = 0
while count <= 10:
count += 1
if count == 5: # 当count等于5时,执行continue,
continue
print('第%s次' % count) # 当执行了continue就会跳过本次打印
print('循环结束!') # 注意缩进!此代码不在循环体内。
4、while...else...
Unlike other languages, Python else can match with while in use
else while the latter refers to the effect of, when executing the normal while loop, with no break, then aborted , else statement will be executed later.
count = 0
while count <= 5:
count += 1
print('第%s次' % count)
else:
print('循环正常执行完了。')
print('循环结束!')
Note: If the break is terminated in the implementation process, it will not execute the else statement.