1.求1-100的总和
1 count = 0 2 int = 0 3 while count < 100: 4 count += 1 5 #print(count) 6 int += count 7 print(int)
2.使用while循环输出1 2 3 4 5 6 8 9 10
1 count = 0 2 while count < 10: 3 count += 1 4 if count == 7: 5 continue #到循环首,不执行下方代码 6 print(count)
1 count = 0 2 while count < 10: 3 count += 1 4 if count == 7: 5 pass #跳过 6 else: 7 print(count)
3.取奇数偶数
count = 0 while count < 100: count += 1 if count % 2 == 0: print('偶数:'+ str(count)) else: #pass print('奇数:'+ str(count))
count = 1 while count < 100: print(count) count += 2
4.1-2+3-4+5-6。。。。99的总和
sum = 0 count = 0 while count < 99: count += 1 #print(count) if count % 2 == 0: sum -= count #如果为偶数就减 else: sum += count #如果为奇数就+ print(sum) #最后结果为50
5.3次机会猜数字游戏
print('接下来我们进行一个猜数字的游戏') print('你共有3次机会,猜出我心中所想的1-10其中一个') count = 0 while count < 3: ni = int(input('请输入1-10其中一个数字:')) if ni == 8: print('恭喜你猜对了!') break else: print('猜错了!你还有' + str(2-count) + '次机会') count += 1
count = 0 while count < 3: username = input('请输入账号:') password = input('请输入密码:') if username == '陈俊' and password == '123': print('登录成功!') break elif count == 2: print('错误次数超过3次!') else: print('登录失败,请检查!你还有' + str(2-count) + '次输入机会!') count += 1