Python - 为什么我的标志无法正常工作以更改为 False 并退出程序

问题描述 投票:0回答:1

我编写了一个 if 语句来检查用户输入是否为“退出”,如果是,则会将活动变量/标志更改为 False,这应该退出我的程序。

所有其他 if 语句都有效,但是当我输入“quit”时,它不会退出程序。相反,我设置的用于检查用户输入中的“退出”的 if 语句似乎被跳过,并且我不断收到错误:

age = int(age)
          ^^^^^^^^
ValueError: invalid literal for int() with base 10: 'quit'

我的代码如下:

prompt = "What is your age? "
prompt += "enter quit if you are finished "
active = True
while active:
    age = input(prompt)
    if age == 'quit':
        active = False
    age = int(age)
    if age < 3:
        print("Your tix is free")
    elif age >= 3 and age <= 12:
        print("Your tix costs $10")
    else:
        print("Your tix costs $15")
python if-statement while-loop flags
1个回答
0
投票

您必须使用

break
:

退出循环
prompt = "What is your age? "
prompt += "enter quit if you are finished "
active = True
while active:
    age = input(prompt)
    if age == 'quit':
        active = False
        break
    age = int(age)
    if age < 3:
        print("Your tix is free")
    elif age >= 3 and age <= 12:
        print("Your tix costs $10")
    else:
        print("Your tix costs $15")
© www.soinside.com 2019 - 2024. All rights reserved.