while循环
while 判断条件( condition) :
执行语句( statements) ……
while循环的跳出
while+break
同for循环一样,只要运行到break就会立刻中止本层while循环
i_num, num = 0 , 5
while i_num <= num:
print ( "loop cycle: %d" % i_num)
i_num += 1
if ( i_num== 2 ) :
print ( "break, jump out of the loop" )
break
else :
print ( "The loop ends normally" )
result:
loop cycle: 0
loop cycle: 1
break , jump out of the loop
while+continue
同for循环一样,只要运行到continue就会立刻中止本层while循环的本次操作,接着回到while后的条件判断,进行下一次循环语句。
i_num, num = 0 , 5
while i_num <= num:
i_num += 1
if ( i_num== 2 ) :
print ( "skip this loop cycle" )
continue
print ( "loop cycle: %d" % i_num)
else :
print ( "The loop ends normally" )
while+else
当迭代对象完成所有迭代后且此时的迭代对象为空时,则执行else子句;如果迭代对象因为某种原因(如带有break关键字)提前退出迭代,则else子句不会被执行,程序将会直接跳过else子句继续执行后续代码(当乖乖执行完while的所有语句,奖励一个else)
i_num, num = 0 , 5
while i_num < num:
print ( "loop cycle: %d" % i_num)
i_num += 1
else :
print ( "The loop ends normally" )
result:
loop cycle: 0
loop cycle: 1
loop cycle: 2
loop cycle: 3
loop cycle: 4
The loop ends normally
while True
循环嵌套
for和while循环可以相互嵌套 break, continue,else也只和本层循环对应
for i in range ( 1 , 4 ) :
for j in range ( 1 , i + 1 ) :
print ( "{}*{}={:<4}" . format ( j, i, i * j) , end= "" )
print ( "" )
result:
1 * 1 = 1
1 * 2 = 2 2 * 2 = 4
1 * 3 = 3 2 * 3 = 6 3 * 3 = 9