为什么While循环继续在以下Python代码中运行?

时间:2018-05-31 05:32:22

标签: python python-3.x while-loop

我是Python的新手,无法弄清楚为什么While循环在以下代码中保持运行?

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")

2 个答案:

答案 0 :(得分:1)

我认为你期望从你的代码...我做了一些改变。你的while循环没有停止因为它没有理由停止。它正在反复测试相同的值

def agetest():
age = input("Please enter the customer's age: ")
age = int(age)
if 0<age <= 3:
    print("Welcome little buddy, no charges for you!")
    agetest()
elif age > 3 and age < 12:
    print("The ticket price is $10")
    agetest()
elif age >= 12:
    print("The ticket price is 15")
    agetest()
elif age == -1:
    print("thnks")

agetest()

这是while循环的答案

age=0
while(age!= -1):

print("Please enter the customer's age: ")
age = int(input())
if 0<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 == -1:
    print("thanks")

答案 1 :(得分:0)

我已经接受了你的代码并进行了一些修改。 问题是:

  1. 你得到了循环的输入,所以它不是交互式的。

  2. 没有声明修改年龄来打破循环。

  3. 如果您希望输入字符串,则无法将输入转换为整数。

     while True:
            prompt = "Please enter the customer's age: "
            age = input(prompt)
            if age == 'quit':
              print("rerun the code")
              break
            elif 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")