Python程序接收非整数输入不崩溃 调用repeatr()重输实现方法
Python非法输入崩溃问题修复
问题原因
你当前代码崩溃的核心原因有3个:
- 直接对
input()的返回值做int()强转,用户输入非整数内容时会触发ValueError导致程序直接终止 - 退出指令
q的判断放在int强转逻辑之后,永远无法匹配到字符串类型的输入,退出功能实际失效 - 输入合法性判断逻辑错误:用
user_input != options对比单个输入值和整个选项列表,判断结果恒为真,会出现合法输入被误判的问题
修复方案
所有接收用户输入的位置统一做三层校验:
- 先判断输入是否为退出指令
q/Q,匹配则直接执行退出逻辑 - 用
try-except捕获整数转换异常,非整数输入直接调用repeatr()提示重输 - 转换为整数后校验是否在允许的选项范围内,不在范围内同样触发重输
修复后的完整可运行代码如下:
import random user_wins = 0 user_draws = 0 user_losses = 0 rounds = 0 def closr(): quit() def repeatr(): print("That is not a valid input. Please input a correct value.") def promptr(): print("Please select an input from the following options.") options = [5, 4, 3, 2, 1] # 原range(1,5)仅包含1-4,调整为range(1,6)覆盖1-5的完整选项 randomlist = random.sample(range(1, 6), 3) randomr = randomlist # 初始菜单输入循环 while True: user_input_raw = input("Type 5/4/3/2/1 or Q to quit.").strip().lower() if user_input_raw == "q": closr() try: user_input = int(user_input_raw) except ValueError: repeatr() continue if user_input in options: break repeatr() # 对局循环 while rounds < 10: promptr() print(f"Current optional choices: {randomlist}") player_choice_raw = input().strip().lower() if player_choice_raw == "q": closr() try: player_choice = int(player_choice_raw) except ValueError: repeatr() continue if player_choice not in randomr: repeatr() continue npc = random.randint(1,5) print("Your opponent has drawn: ", npc) if npc > player_choice: print("You have been defeated this round.") user_losses = user_losses + 1 print("The score is:" , user_wins , ":" , user_losses) rounds = rounds + 1 elif npc < player_choice: print ("You have won this round.") user_wins = user_wins + 1 print ("The score is:" , user_wins , ":" , user_losses) rounds = rounds + 1 elif npc == player_choice: print ("You have drawn this round.") user_draws = user_draws + 1 print ("The score is:" , user_wins , ":" , user_losses) rounds = rounds + 1 if user_losses < user_wins: print("You have won the game!") elif user_losses > user_wins: print("You have lost this game. Better luck next time!") elif user_losses == user_wins: print("The game has ended in a draw.") print("the number of wins you had was:" , user_wins) print("the number of draws you had was:" , user_draws) print("the number of losses you had was:" , user_losses) print("The final score was (Player vs CPU):" , user_wins, ":" , user_losses) # 结束退出循环 while True: resu=input("Press Q to quit the game.").strip().lower() if resu=="q": closr()
额外调整说明
- 去掉了原代码中无意义的
x/y/u循环标记变量,直接用while True+break实现循环控制,逻辑更清晰 - 给对局阶段的输入加了可选选项提示,避免用户不知道可输入的值范围
- 所有输入统一做了首尾去空格、小写转换,避免用户误输空格、大写Q导致判断失效
- 修正了原
random.sample的取值范围,现在会从1-5的完整选项中抽取3个可选值,和初始菜单的选项范围一致
内容的提问来源于stack exchange,提问作者SuspiciouslyQuiet
相关产品推荐
相关产品推荐

