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

Python程序循环异常:如何让huh()执行后返回原问题而非重复?

问题解决思路

你的问题核心是**open_question函数的输入位置错误**:pyq1 = input(...)写在了while not valid循环外面,导致第一次输入无效后,循环会一直复用这个旧值反复进入else分支调用huh(),形成死循环。另外huh()函数里的内部while循环完全多余——不管用户输入什么,你都会把washappening设为True,直接去掉就能简化代码。

修改后的代码

import random  # 补充原代码缺失的导入

def huh(): 
    typo = input("i dont understand? Did you make a typo??")
    if typo.lower() == "yes":
        print("oh, no worries ill just ask the question again")
    elif typo.lower() == "no":
        print("o....k.... I still dont understand so try the question again")
    else:
        print("""aaaaand even more words i dont understand... i should look at a dictionary.
anyways try the question again but maybe with a simpler question?""")

def open_question():
    # 假设language和goodwords为外部已定义变量
    if language.lower() == "python":
        print(f"SAME! its quite easy so i like it quite a lot, would be even more {random.choice(goodwords)} if (cant think of anything)")

        valid = False
        while not valid:
            # 将输入移到循环内部,每次循环都会重新提问
            pyq1 = input("do you make a lot of programs? ")
            pyq1_processed = pyq1.lower().strip()
            if pyq1_processed == "yes":
                print("wow, we're very alike")
                valid = True
            elif pyq1_processed == "no":
                print("understandable, programming can take some time" )
                valid = True     
            elif pyq1_processed in ["a bit", "a little", "a little bit", "kinda"]:
                print("understandable, programming can take some time")
                valid = True
            else:
                huh()

关键改动说明

  • 把pyq1 = input(...)移动到while not valid循环内部,确保调用huh()后,循环会重新获取用户的新输入,而非一直复用旧值。
  • 移除huh()函数内多余的while循环,逻辑不变但代码更简洁。
  • 用.lower()和.strip()统一处理输入,用列表in操作简化多选项判断,减少冗余代码,提升可维护性。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.28 11:32:42