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

Python开发‘何必担忧’交互程序时while循环输入校验逻辑异常求助

你现有代码的核心问题有两个:

  • 两层while循环都没有在输入非法时重新触发用户输入的逻辑,仅打印提示后会继续执行后续代码,无法实现重复问询的效果
  • 第二层循环的elif没有附带判断条件,属于语法错误,会直接运行报错

以下是修正后可正常运行的代码,完全匹配「那何必担忧」的逻辑流程:

while True:
    # 第一层问询:是否存在问题
    problem = input("Do you have a problem in life? ").replace(" ", "").lower()
    if problem not in ("yes", "no"):
        print("Please enter YES or NO")
        # 输入非法直接回到循环开头重新获取输入
        continue
    if problem == "no":
        # 没有问题直接跳出外层循环
        break
    # 走到此处说明输入为yes,进入第二层问询
    while True:
        something = input("Do you have something to do about it? ").replace(" ", "").lower()
        if something not in ("yes", "no"):
            print("Please enter YES or NO")
            continue
        # 输入合法直接跳出内层循环
        break

print("Then why worry?")

如果需要使用中文交互,仅需把input里的提示文本和print的输出内容替换为中文即可。

内容的提问来源于stack exchange,提问作者Shoshan Ben-Tzvi

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 01:45:00