You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何优化while循环处理无效输入?避免重复编写代码

优化输入验证逻辑,避免重复代码

原始代码

door = input("Do you want to open the door? Enter yes or no: ").lower()

while door != "yes" and door != "no":
    print("Invalid answer.")
    door = input("Do you want to open the door? Enter yes or no: ").lower()

if door == "yes":
    print("You try to twist open the doorknob but it is locked.")
elif door == "no":
    print("You decide not to open the door.")

问题需求

通过循环处理用户无效输入,但不想每次都重复编写输入语句,尝试过def()和while True但不知如何正确使用。

解决方案:封装通用验证函数

把输入验证逻辑封装成可复用的函数,只需一次定义,多次调用,彻底避免重复代码。

def get_valid_input(prompt, valid_options):
    # 无限循环直到获取合法输入
    while True:
        user_input = input(prompt).lower()
        # 检查输入是否在合法选项中
        if user_input in valid_options:
            return user_input
        # 输入无效时提示
        print("Invalid answer.")

# 调用函数获取合法输入
door = get_valid_input("Do you want to open the door? Enter yes or no: ", ["yes", "no"])

# 后续逻辑不变
if door == "yes":
    print("You try to twist open the doorknob but it is locked.")
elif door == "no":
    print("You decide not to open the door.")

函数优势

  • 复用性强:后续其他需要输入验证的场景,直接调用该函数即可,比如:
    # 示例:获取颜色选择
    color = get_valid_input("Enter your favorite color (red/blue/green): ", ["red", "blue", "green"])
    
  • 逻辑统一:所有输入验证的规则集中在函数里,后续修改规则只需改一处
  • 代码简洁:不用重复编写input和循环判断语句

内容的提问来源于stack exchange,提问作者fuwubuki

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.11 12:15:31