Minecraft服务器软件输入校验逻辑失效,为何无法拦截无效输入?
问题原因及修复方案
你的代码无法拦截无效输入的核心问题是if语句的逻辑判断错误。
错误原因分析
你写的条件:
if configuration_type == "vanilla" or "forge" or "spigot" or "bukkit" or "paper":
在Python里会被拆解成:(configuration_type == "vanilla") or ("forge") or ("spigot") or ("bukkit") or ("paper")
而任何非空字符串在布尔判断中都会被视为True,所以不管configuration_type的值是什么,后面的几个字符串都会让整个条件结果为True,导致config_type_check直接被设为False,循环立即结束,根本不会走到else分支去重新输入。
修复后的代码
推荐用in关键字简化判断,同时优化循环逻辑:
config_type_check = True valid_types = ["vanilla", "forge", "spigot", "bukkit", "paper"] while config_type_check: configuration_type = input(f"Please enter a valid server installation type ({'/'.join(valid_types)}): ") if configuration_type in valid_types: config_type_check = False else: print("You have entered an invalid selection.")
如果要保留你原有的结构,需修正if条件:
config_type_check = True # 先初始化输入变量 configuration_type = input("Please enter a valid server installation type: ") while config_type_check: if configuration_type == "vanilla" or configuration_type == "forge" or configuration_type == "spigot" or configuration_type == "bukkit" or configuration_type == "paper": config_type_check = False else: configuration_type = input("You have entered an invalid selection. Please enter a valid server installation type.")
额外优化提示
- 用
while config_type_check代替while config_type_check == True,更符合Python简洁风格 - 将合法选项存入列表,后续新增类型时只需修改列表,无需改动判断逻辑
内容的提问来源于stack exchange,提问作者duebin.1
相关产品推荐
相关产品推荐

