Python验证输入是否在列表内 输入预设退出命令未触发程序退出问题
代码问题排查与修复
核心故障原因
Exit_Commands列表的各字符串元素之间没有加逗号分隔,Python 会默认拼接相邻无分隔的字符串常量,你定义的列表实际仅包含1个拼接后的长字符串"ExitexitGoodbyegoodbyebyebye",不存在你预期的单个退出命令选项,因此输入匹配判断永远不会触发。
修正后的完整代码
from sys import exit Exit_Commands = [ "Exit", "exit", "Goodbye", "goodbye", "Bye", 'bye' ] Alive = True while Alive: User_Input_From_Console = input() if User_Input_From_Console in Exit_Commands: print("Exiting Program") exit()
可选优化建议
如果不想在列表里枚举所有大小写组合,可以直接将用户输入转为小写后和小写命令匹配,简化代码同时避免大小写漏判问题:
from sys import exit Exit_Commands = {"exit", "goodbye", "bye"} # 用集合做成员查询效率更高 while True: user_input = input().strip().lower() if user_input
相关产品推荐
相关产品推荐

