while循环
结构:
while循环 (难点) while 条件: 循环体(break, continue)
break # 直接跳出循环
while True: content = input("请输入你要喷的内容, 输入Q退出") if content == "Q": # 退出程序 打断循环 break # 直接跳出循环 print("你对打野说:", content)
if True: print("娃哈哈")
最多喷三次 count = 1 while count <= 3: # count = 1 # 次数, 死循环 content = input("请输入你要喷的内容") print("你要对上单说:", content) # 改变count count = count + 1
continue while True: content = input("请输入你要喷的内容, 输入Q退出") if content == "": continue # 停止当前本次循环. 继续执行下一次循环 不会彻底中断循环. if content == "Q": # 退出程序 打断循环 break # 直接跳出循环 print("你对打野说:", content)
能够让循环退出: 1. break 2. 改变条件
continue 停止当前本次循环. 继续执行下一次循环 break 彻底的干掉一个循环
让程序从1数数, 数到100
count = 1 while count <= 100: print(count) # 1 count = count + 1
计算 1-100之间所有的数的和
sum = 0 # sum: 0 + 1 + 2 + 3 + 4....99 + 100 count = 1 # count: 1, 2, 3, 4, 99,100, 101 while count <= 100: sum = sum + count # 累加运算 count = count + 1 print(sum)
数数. 1-100奇数
count = 1 while count <= 100: print(count) count = count + 2
count = 1 while count <= 100: if count % 2 == 1: print(count) else: print("偶数....") count = count + 1