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

Python脚本问题:重复提问且输入4时循环无法终止

问题解决

核心问题分析

  1. 未处理输入"4"的合法分支,导致输入4时直接进入else触发无限循环
  2. 若仅需单次提问,while True循环完全多余;若需要输入错误时重新提问,原代码未在循环内重新获取输入,变量值始终不变

方案1:仅提问一次,输出对应内容

去掉冗余循环,补充对"4"的判断逻辑:

def quest2():
    q2 = input("\nWhat's your prefered beverage? \n\t1. Beer \n\t2. Wine \n\t3. Vodka \n\t4. I don't drink alcohol (Answer with: 1, 2, 3 or 4)")
    return q2

variable1 = quest2()

if variable1 == "1":
    print("\nYou went the safe route")
elif variable1 == "2":
    print("\nSomeone has some fine taste")
elif variable1 == "3":
    print("\nYou build your own stuff")
elif variable1 == "4":
    print("\nRespect for your choice!")
else:
    print("\nInvalid input, please enter 1, 2, 3 or 4 next time.")

方案2:输入错误时重新提问,直到输入合法

将获取输入的函数调用放入循环内部,确保每次循环更新输入值,同时补充"4"的处理分支:

def quest2():
    q2 = input("\nWhat's your prefered beverage? \n\t1. Beer \n\t2. Wine \n\t3. Vodka \n\t4. I don't drink alcohol (Answer with: 1, 2, 3 or 4)")
    return q2

while True:
    variable1 = quest2()
    if variable1 == "1":
        print("\nYou went the safe route")
        break
    elif variable1 == "2":
        print("\nSomeone has some fine taste")
        break
    elif variable1 == "3":
        print("\nYou build your own stuff")
        break
    elif variable1 == "4":
        print("\nRespect for your choice!")
        break
    else:
        print("\nInvalid input, please try again.")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.19 13:30:11