while循环
1. 使用while循环输出1 2 3 4 5 6 8 9 10
count = 0 while count < 10: count += 1 if count == 7: continue print(count)
2. 求1-100的所有数的和
count = 0 i = 0 while count <100: count += 1 i += count print(i)
3. 输出 1-100 内的所有奇数
count = 0 while count < 100: count += 1 if count % 2 == 1: print(count)
4. 输出 1-100 内的所有偶数
count = 0 while count < 100: count += 1 if count % 2 == 0: print(count)
5. 求1-2+3-4+5 ... 99的所有数的和
count = 0 i = 0 while count < 100: count += 1 if count % 2 == 0: i -= count else: i += count print(i)
6. 用户登陆(三次机会重试)
account_dic = {'avery': '123', 'kaia': '456', 'black_girl': '789'} count = 0 while count < 3: # 计数使用三次 count += 1 account = input('账号') password = input('密码') if account in account_dic: # 当账号输入正确时 if password == account_dic[account]: # 密码输入正确 print('登陆成功') break elif count == 3: print('对不起,输入错误三次,系统即将退出') break else: print('密码错误,请重新输入') continue elif count == 3: # 输入错误三次提示 print('对不起,输入错误三次,系统即将退出') else: print('账号输入错误,请重新输入')
7. 猜年龄游戏
print('猜年龄游戏') age_of_avery = 18 count = 0 res = 3 while count < 3: count += 1 res -= 1 number = int(input('输入你认为avery的年龄')) if number == age_of_avery: print('恭喜你猜对了') break elif number < age_of_avery: print('谢谢,我很满意,但是你猜错了') print(f'你还有{res}次机会') else: print(f'你全家都{number}岁') print(f'你还有{res}次机会')
猜年龄游戏升级版(选做题)
# 要求:允许用户最多尝试3次,每尝试3次后,如果还没猜对,就问用户是否还想继续玩,如果回答Y或y, 就继续让其猜3次,以此往复,如果回答N或n,就退出程序,如果猜对了,就直接退出 print('猜年龄游戏') age_of_avery = 18 count = 0 res = 3 while count < 3: # 判断年龄是否正确 count += 1 res -= 1 number = int(input('输入你认为avery的年龄')) if number == age_of_avery: print('恭喜你猜对了') break elif number < age_of_avery: print('谢谢,我很满意,但是你猜错了') print(f'你还有{res}次机会') # elif number > age_of_avery: else: print(f'你全家都{number}岁') print(f'你还有{res}次机会') if count == 3: # 是否继续进行游戏 word = input('次数已用尽,是否继续,继续请输入Y/y,退出请输入N/n:') if word == 'Y' or word == 'y': print('继续猜吧') count = 0 res = 3 # elif word == 'N' or word == 'n': else: print('小子,你差远了') break