Python假期目的地选择脚本无法输出预期结果问题求助
代码修正方案
原代码核心问题
- 缺失用户选项采集逻辑:打印度假选项后没有调用
input()接收用户的选择结果 - 函数判断逻辑错误:函数内部错误将函数名
choose_location作为对比对象,完全没有关联用户的实际输入 - 无异常输入兼容:用户输入小写选项、带空格的内容或其他非法字符时没有对应提示
修改后完整代码
print("Congratulations! You have won an all-inclusive vacation!\n") # 接收姓名输入,如后续无需使用可不用赋值保留 input("Please enter your first and last name\n") print("Please choose where would you like to go on vacation?\n" "A. The Bermuda Triangle\n" "B. Space\n" "C. Antarctica\n") # 采集用户选择,自动去首尾空格+转大写,兼容小写输入场景 user_choice = input("Enter your choice (A/B/C): ").strip().upper() def choose_location(choice): if choice == "A": print("You chose The Bermuda Triangle") elif choice == "B": print("You chose Space") elif choice == "C": print("You chose Antarctica") else: print("Invalid option, please only enter A/B/C.") choose_location(user_choice)
修改说明
- 新增用户选项采集步骤,通过
input()拿到用户的选择内容,添加的strip()和upper()方法可以兼容用户输入小写字母、前后带空格的场景 - 给
choose_location函数添加了choice入参,判断逻辑改为对比传入的用户选择内容,修复了原判断永远不生效的问题 - 新增非法输入的处理分支,用户输入不符合要求时会返回错误提示
内容的提问来源于stack exchange,提问作者SlothJesus
相关产品推荐
相关产品推荐

