Skip to main content
 首页 » 编程设计

python之在 Python 中,else block 可以有更多的 if-elif-else block 吗

2025年05月04日13haluo1

电影票:电影院根据一个人的年龄收取不同的票价。未满 3 岁者免票;如果他们在 3 到 12 之间,则票价为 10 美元;如果他们超过 12 岁,票价为 15 美元。编写一个循环,询问用户的年龄,然后告诉他们电影票的费用。

我希望这个程序具有退出值(value)。我本可以使用 0 作为退出值,但我想使用“退出”。

prompt = "What is your age? " 
prompt += "\nEnter 'quit' to close program." 
 
age = 0 
 
while True: 
 
 
     age = raw_input(prompt) 
        if age == 'quit': 
            break 
        else: 
            age = int(age) 
            if age < 3: 
                print("The movie ticket is FREE for you.") 
            elif 3 <= age < 12: 
                print("The movie ticket is $10 for you.") 
            elif age >= 12: 
                print("The movie ticker is $15 for you.") 

请您参考如下方法:

我想指出您不需要 else 子句。您可以在前面的缩进级别包含其余条件,因为 break 退出循环而不是继续循环体的其余部分。

而不是

    if age == 'quit': 
        break 
    else: 
        age = int(age) 

简单地:

    if age == 'quit': 
        break 
 
    age = int(age) 

如果这不是很清楚,这里是整个程序的变化:

prompt = "What is your age? " 
prompt += "\nEnter 'quit' to close program." 
 
while True: 
 
    age = raw_input(prompt) 
    if age == 'quit': 
        break 
 
    age = int(age) 
    if age < 3: 
        print("The movie ticket is FREE for you.") 
    elif 3 <= age < 12: 
        print("The movie ticket is $10 for you.") 
    elif age >= 12: 
        print("The movie ticker is $15 for you.") 

我还删除了无用的赋值:age = 0,因为该值在被读取之前被替换为 age = raw_input(prompt)。