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

为什么带有if语句的while循环无法正常运行?该如何修复?

问题根因
  • 正确答案无响应:while循环的触发条件为answer != "8",用户首次输入正确答案时不会进入循环体,写在循环内部的正确提示语句永远不会执行。
  • 错误答案死循环:进入循环后没有重新获取用户输入,answer变量一直是第一次输入的错误值,循环条件永远为真,导致无限输出错误提示。
    另外原代码开头的answer = "8"属于冗余初始化,后续input()会直接覆盖该值,可直接删除。
修复方案

方案1:调整原有代码逻辑

把正确提示移到循环外,循环内新增重新获取输入的逻辑:

print("What is 5 + 3 = ? ")
answer = input()

while answer != "8":
    print("Incorrect answer!")
    print("What is 5 + 3 = ? ")
    answer = input()

print("Correct answer!")

方案2:更简洁的写法

用while True+break的结构,避免重复写提问代码,逻辑更清晰:

while True:
    answer = input("What is 5 + 3 = ? ")
    if answer == "8":
        print("Correct answer!")
        break
    print("Incorrect answer!")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 07:15:04