for循环
for i in range(): #注意冒号 range中默认从0开始 或者从指定的数字开始 到给定数字的前一个数字结束 递增递减皆是如此
for循环提供变量的自动初始化
for i in range(10): print(i,end = ‘ ‘) print() for i in range(5,10): print(i,end = ‘ ‘) print() for i in range(10,0,-1): print(i, end = ‘ ‘) print()
>>> ================================ RESTART ================================ >>> 0 1 2 3 4 5 6 7 8 9 5 6 7 8 9 10 9 8 7 6 5 4 3 2 1
while循环:
需要自己初始化,可以包含一个else语句块
i = 0 while i < 10: print(i,end = ‘ ‘) i = i + 1 print()
当事先循环次数不确定时,无法用for循环 如:
#donesum.py total = 0 s = input(‘input a number or "done":‘) while s != ‘done‘: total = total + int(s) s = input(‘input a number or "done":‘) print(‘the total is ‘ + str(total))
break #跳出循环
continue #进入下一次循环 少用较好
多层循环:
#timestable.py for row in range(1,10): for col in range(1,10): prod = row * col if prod < 10: print(‘ ‘, end = ‘‘) print(row * col, " ", end = ‘‘) print()
>>> ================================ RESTART ================================ >>> 1 2 3 4 5 6 7 8 9 2 4 6 8 10 12 14 16 18 3 6 9 12 15 18 21 24 27 4 8 12 16 20 24 28 32 36 5 10 15 20 25 30 35 40 45 6 12 18 24 30 36 42 48 54 7 14 21 28 35 42 49 56 63 8 16 24 32 40 48 56 64 72 9 18 27 36 45 54 63 72 81
时间: 2024-10-31 22:14:38