Python中While True循环内If语句重复输出无效输入直至崩溃问题求助
问题分析与解决方法
问题根源
- 输入未在循环内更新:你把
option2 = input("> ")放在了while True循环外面,用户仅在程序启动时输入一次,之后循环反复判断的始终是第一次的输入值。如果第一次输入不是"1"或"2",循环会无限执行else分支,永远无法获取新输入。 - 分支缺少退出逻辑:当用户输入"2"时,代码没有
break语句,执行完print后会继续循环,同样陷入重复判断旧输入的死循环。
修正后的代码
print("You can see a faint outline of a coast in the distance... you can either: 1. paddle to the island on the raft ; 2. swim to the island") while True: option2 = input("> ") # 将输入移至循环内,每次循环都重新获取用户输入 if option2 == "1": print("The raft fully sinks... you are left in the freezing cold water. You spent all your energy trying to keep the raft afloat. You have made your demise inevitable") break # 执行完成后退出循环 elif option2 == "2": print("You jump headfirst into the cold water... not really a good idea, but you seem to have insane swimming skills. Are you Michael Phelps? Anyways you make it to the shore seconds before fainting") break # 新增break,避免输入2后继续循环 else: print("Invalid input: Please select one of the options above")
补充说明
while True是无限循环,会持续执行内部代码直到遇到break语句。因此必须确保循环内有能改变判断条件的操作(比如重新获取输入),或在符合预期条件时用break退出循环,避免无限执行。
内容的提问来源于stack exchange,提问作者Rotortr
相关产品推荐
相关产品推荐

