Python猜水果游戏重玩/退出输入逻辑失效问题解决
解决Python猜水果游戏重启逻辑失效问题
问题还原
编写了一个简易Python猜水果游戏,在restart()函数中设置了输入yes重启游戏、no退出游戏的逻辑,但无论输入yes或no,都会触发"Sorry i didn't get that."提示,多次输入也无法触发对应功能;移除代码中的.lower()方法后,问题解决。
错误代码示例
问题出在输入转换与判断条件的大小写不匹配,典型错误代码如下:
def play_game(): # 猜水果游戏核心逻辑 print("Guess the fruit!") def restart(): choice = input("Do you want to play again? (yes/no): ").lower() # 错误:判断条件用大写字符串,与转换后的小写输入不匹配 if choice == "Yes": play_game() elif choice == "No": print("Thanks for playing!") exit() else: print("Sorry i didn't get that.") restart() play_game() restart()
修复方案
方案1:移除.lower()(快速解决但不健壮)
直接去掉输入转换的.lower(),此时用户输入必须和判断条件的大小写完全一致才能匹配:
def restart(): choice = input("Do you want to play again? (yes/no): ") if choice == "Yes": play_game() elif choice == "No": print("Thanks for playing!") exit() else: print("Sorry i didn't get that.") restart()
方案2:统一大小写匹配(推荐,更健壮)
保持.lower()转换输入为小写,同时将判断条件改为小写字符串,兼容用户输入的任意大小写形式:
def restart(): choice = input("Do you want to play again? (yes/no): ").lower() if choice == "yes": play_game() elif choice == "no": print("Thanks for playing!") exit() else: print("Sorry i didn't get that.") restart()
问题原因
使用.lower()将用户输入转为全小写后,判断条件却使用了大写的"Yes"/"No",导致字符串匹配失败("yes"与"Yes"不相等、"no"与"No"不相等),所有输入都会进入else分支触发错误提示。移除.lower()后,用户输入的大小写与判断条件一致时就能匹配,但这种方式无法兼容不同大小写的输入;推荐使用统一小写的匹配方式,提升代码健壮性。
内容的提问来源于stack exchange,提问作者ItsMeData
相关产品推荐
相关产品推荐

