while循环格式
while 条件:
循环体(break, continue)
例子
1 while True: 2 content = input("请输入你要喷的内容,输入Q退出") 3 if content == "Q": 4 # 退出程序 打断循环 5 break # 直接跳出循环 6 print("你对打野说:", content)
1 count = 1 # 次数 2 while count <= 3: 3 content = input("请输入你要喷的内容") 4 print("你要对上单说:", content) 5 # 改变content 6 count = count + 1
计算1-100的和
1 sum = 0 # sum: 0 + 1 + 2 + 3 + 4.....99 + 100 2 count = 1 # count:1, 2, 3, 4, 99, 100, 101 3 while count <= 100: 4 sum = sum + count # 累加运算 5 count = count + 1 6 print(sum)
输出1-100所有奇数或偶数
奇数
1 num3 = 1 2 while num3 <= 100: 3 if num3 % 2 == 1: 4 print(num3) 5 num3 += 1
偶数
1 num3 = 1 2 while num3 <= 100: 3 if num3 % 2 == 0: 4 print(num3) 5 num3 += 1