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

技术咨询:为何下述Python代码中的while循环持续运行?

解决你的while循环持续运行问题

嘿,我来帮你捋清楚这个问题!作为Python初学者碰到这种循环停不下来的情况太正常了,咱们拆解一下你的代码问题:

首先先看看你原有的代码:

prompt = "Please enter the customer's age: "
age = input(prompt)
while age != 'quit':
    age = int(age)
    if age <= 3:
        print("Welcome little buddy, no charges for you!")
    elif age > 3 and age < 12:
        print("The ticket price is $10")
    elif age >= 12:
        print("The ticket price is 15")
    elif age == 'quit':
        print("rerun the code")

问题1:循环内没有重新获取用户输入

你在循环开始前只获取了一次age = input(prompt),进入循环后把age转成了整数,但之后再也没有让用户输入新的内容!这就导致age一直是你第一次输入的那个整数,永远不可能等于字符串'quit',循环自然会无限跑下去。

问题2:类型不匹配+条件分支顺序错误

你把age转成整数之后,再判断age == 'quit'完全没有意义——整数和字符串根本不可能相等。而且前面的三个条件已经覆盖了所有整数的情况(小于等于3、3到12之间、大于等于12),最后那个elif分支永远都不会被执行到。

修正后的代码

我帮你调整了逻辑,先判断用户是不是输入了quit,再处理年龄的计算,同时每次循环结束后重新获取输入:

prompt = "Please enter the customer's age (or 'quit' to exit): "
while True:
    age = input(prompt)
    # 先判断是否要退出
    if age == 'quit':
        print("Exiting the program...")
        break
    # 尝试把输入转成整数,处理用户输入非数字的情况
    try:
        age = int(age)
        if age <= 3:
            print("Welcome little buddy, no charges for you!")
        elif 3 < age < 12:
            print("The ticket price is $10")
        elif age >= 12:
            print("The ticket price is $15")
    except ValueError:
        print("Please enter a valid number or 'quit'!")

修正点说明

  • 用while True创建一个无限循环,通过break来主动退出,逻辑更清晰
  • 每次循环开头先获取新的用户输入,确保能响应新的操作
  • 先检查是否输入了quit,满足条件就直接跳出循环
  • 加入try-except处理用户输入非数字的情况,避免程序崩溃
  • 调整了价格的格式,把15改成$15保持统一

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.29 08:36:05