1.死循环
while 1 == 1: print('ok')
结果是一直循环
2.循环
count = 0while count < 10: print(count) count = count +1print(error)
3.练习题
~ 使用while循环输出1 2 3 4 5 6 8 9 10
count = 1while count <= 10 : # 或者count < 11 if count == 7: print( ) # 也可以添加pass,什么也不执行 else: print(count) count = count + 1
执行结果:
1234568910Process finished with exit code 0
~ 求1-100的所有数的和
a = 1b = 0while a < 101: b = b + a a = a + 1print(b)
输出结果:
5050Process finished with exit code 0
~求1-100内所有的奇数
n = 1while n < 101: js = n % 2 if js == 0: print( ) else: print(n) n = n + 1
输出结果:
13579111315171921232527293133353739414345474951535557596163656769717375777981838587899193959799
~ 求1-100内所有的偶数
a = 1while a < 101: b = a % 2 if b == 0: print(a) else: pass a = a + 1
输出结果:
2468101214161820222426283032343638404244464850525456586062646668707274767880828486889092949698100Process finished with exit code 0