Python while True循环失效求助:冒险游戏脚本二次循环终止
解决冒险游戏中的循环问题
问题原因
- 缩进错误:第二个
while True循环内的代码存在缩进不一致(比如fightOrRun = input()那行缩进不足),Python是严格依赖缩进的语言,这会直接触发语法错误,导致脚本终止运行。 - 逻辑错误:第一个循环已经确保
fightOrRun的值只能是1/1.或2/2.,所以第二个循环里的else分支永远不会执行;同时每个if/elif块内直接break,根本没有对用户的新输入做有效性检查,自然无法实现“输入无效就循环”的效果。
修正后的代码
import time # 第一个选择:战斗还是逃跑 while True: print('A man approaches you with his sword drawn and an angry look spread across his face, what do you do?') print('1. Run away') print('2. Punch the man') fightOrRun = input().strip() # 去除输入前后空格,提升容错性 if fightOrRun in {'2', '2.'}: print('Man: "You\'re going to get it!"') break elif fightOrRun in {'1', '1.'}: print('Man: "Where do you think you\'re going!"') break else: print('Not a valid input!') continue # 第二个选择:根据之前的选项处理新输入 while True: if fightOrRun in {'2', '2.'}: print('1. Adios loser!') user_choice = input().strip() # 检查新输入是否有效,有效则退出循环 if user_choice == '1': print('You taunt the man and escape!') break else: print('Please enter a valid input!') continue elif fightOrRun in {'1', '1.'}: print('1. I don\'t know') print('2. I\'m sorry') user_choice = input().strip() # 检查新输入是否有效 if user_choice in {'1', '2', '1.', '2.'}: if user_choice in {'1', '1.'}: print('You stammer nervously...') else: print('The man calms down a little.') break else: print('Please enter a valid input!') continue
修改说明
- 修复了所有缩进错误,确保代码符合Python语法规范。
- 对用户输入使用
strip()方法去除前后空格,提升输入容错性(比如用户输入空格+1也能识别)。 - 第二个循环中新增了对用户新输入的有效性检查,只有当输入符合要求时才会
break退出循环,否则提示错误并继续循环。 - 修正了原文中的拼写错误(比如
Your改为You're,dont改为don't等),提升文本准确性。
内容的提问来源于stack exchange,提问作者Virtx_x
相关产品推荐
相关产品推荐

