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

Python输入验证代码无法跳转至指定循环节点问题求助

问题根因
  • 初始化逻辑错误:开头直接将空字符串num_stores = ""强转为整型,程序启动就会抛出ValueError异常,根本无法执行到后续循环逻辑。
  • 循环嵌套逻辑错误:两个校验规则(输入必须为数值、数值必须≤10)是平级的先后校验关系,不应嵌套写为两层while循环,原代码中数值范围校验的while循环触发条件初始不成立,自然不会执行。
  • 缺少合法输入的终止逻辑:就算输入符合要求,原代码也没有跳出循环的判断,会一直重复要求用户输入。
修正后可运行代码
# 初始化变量,不提前做int转换避免启动报错
num_stores = ""
num_stores_int = 0

while True:
    num_stores = input("\n To start, please enter the amount of stores you own: ")
    # 第一重校验:是否为纯数值
    if not num_stores.isnumeric():
        print ("\n Hey, uhh, you're going to have to write a number for the\n amount of stores you've got, letters and decimals don't \n really work. Here, try again, I'll reboot it for you.\n")
        print (" -----------------------REBOOTING------------------------")
        continue
    # 转换为整型后做第二重校验
    num_stores_int = int(num_stores)
    if num_stores_int > 10:
        print (" Sorry, this sales tracker can track a maximum of 10 stores.\n Here, try that again, I'll reboot it for you.\n")
        print (" -----------------------REBOOTING------------------------")
        continue
    # 校验全部通过,执行业务逻辑
    if num_stores_int >= 5:
        print ("\n Hmm, interesting, you'd think someone with that many \n stores would be able to afford a better sales tracker.")
        print (" Well, I guess you're stuck with me! MUHAHAHAHA!!......\n\n Anyway,")
        print (f" clearly big business person, you own {num_stores_int} stores.\n I'm gonna need you to tell me where each one is")
    else:
        print (f" Alright... so, random business person, you have {num_stores_int} stores.\n Now, I'm going to need you to tell me where each one is")
    # 结束校验,跳出循环
    break
逻辑说明

只用一层外层循环控制校验流程,每次循环先获取用户输入:

  1. 先判断输入是否为纯数值,不符合要求就提示重试,直接进入下一轮循环
  2. 输入为数值则转换为整型,判断是否超过10,不符合要求就提示重试,直接进入下一轮循环
  3. 两个校验都通过后执行对应提示逻辑,最后跳出循环结束输入校验流程

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.25 03:06:04