为什么lower()函数在我的Python文本冒险游戏中不起作用?
问题排查与修复
你的代码里大小写不敏感判断失效的核心原因很明确:
- 你把用户输入用
lower()转成了小写,但判断时却和大写开头的字符串(比如"Stay"、"Yes")做比较,两边永远无法匹配。 - 另外
while循环里的输入逻辑有问题,用户输入错误后不会重新获取输入,会陷入死循环。
修正后的代码
import time StayEnding = False def intro(): global StayEnding print("You wake up in your room like usual.") time.sleep(1) print("But this time, something was different.") time.sleep(1) print("You can feel power rushing down to your body, magic flowing through your veins.") time.sleep(1) print("Are you powerful? Can you cast magic? You shouldn't know now. It's time to go.") userinput = input("Do you want to stay or go? ").strip().lower() if userinput == "stay": print("You never went outside, you decided to stay in your house.") time.sleep(1) print("You got the Stay Ending.") StayEnding = True while True: reset_input = input("Would you like to reset? ").strip().lower() if reset_input == "yes": time.sleep(3) intro() elif reset_input == "no": print("Farewell. Remember that you can't save.") quit() else: print("What are you even trying to say?") continue intro()
关键修改点
- 统一大小写匹配:把用户输入转成小写后,和全小写的目标字符串比较(比如
"stay"、"yes"),同时用strip()去掉输入前后的空格,避免用户误输入空格导致匹配失败。 - 修复循环输入逻辑:把重置的输入语句
reset_input = input(...)放到while True循环内部,这样用户输入错误后会重新提示输入,而不是一直重复错误提示。 - 补充缺失的导入:代码里用到了
time.sleep(),需要在开头加上import time,否则会报错。
内容的提问来源于stack exchange,提问作者Arkan Gaming
相关产品推荐
相关产品推荐

