Python while循环运行,但int()使用不正确,无法输入'quit'

2024-06-02 21:57:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在完成Eric Matthes的Python速成班的教科书作业

代码按照说明运行,但我想解决三个问题,但不知道如何解决。问题是:(1)我不知道我是否正确使用了该标志。(2) 我使用int()操作用户输入,以便将用户值与整数进行比较。(3) 如果用户输入'quit',程序将崩溃并显示错误(ValueError:int()的无效文本,以10为基数:“quit”)。这与我的第二期有关

谢谢你的帮助

大卫

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

prompt = "\nI will price your ticket. What is your age?"

active = True #Per Matthes, using the flag Active, a program "should run while 
#the flag is set to True and stop running when any of several events sets the 
#value of the flag to False."  
while active:
    message = int(input (prompt))

    if message < int(3):
        print("Your ticket is free!")
    elif int(3) <= message <= int(12):
        print("Your ticket is $10!")
    elif message > int(12):
        print("Your ticket is $15!")
    else:
        active = False
        break #Per Matthes, the break statement will force the program "to exit
        #a while loop immediately without running any remaining code in the 
        #loop." 

Tags: theto用户messageyouristicketquit
2条回答

您可以尝试使用异常处理

try:
    message = int(input (prompt))
except:
    print("You've entered an invalid input")
    break

如果这是你的问题,这将解决它

因此,评论也这么说,但以下是完整的解释:

  1. 要求用户输入年龄。无论您输入什么年龄,它都符合三个条件之一,因此输入的任何年龄都不会触发“else”条件

  2. 触发else的唯一方法是输入非整数,如单词或字母,但行message = int(input (prompt))尝试将输入转换为整数,因此输入任何其他内容都将引发异常

  3. 您可以使用异常处理程序或通过实现执行退出响应的特定整数(如零)来解决此问题

下面是一个带有异常处理程序的示例:

prompt = "\nI will price your ticket. What is your age?"

active = True 
#Per Matthes, using the flag Active, a program "should run while 
#the flag is set to True and stop running when any of several events sets the 
#value of the flag to False."  
while active:

    message = input (prompt)
    try:
        message = int(message)
        if message < int(3):
            print("Your ticket is free!")
        elif int(3) <= message <= int(12):
            print("Your ticket is $10!")
        elif message > int(12):
            print("Your ticket is $15!")
    except:
        active = False
        print("\nGoodbye!")

这里有一个输入零将触发退出:

prompt = "\nI will price your ticket. What is your age?"

active = True 
#Per Matthes, using the flag Active, a program "should run while 
#the flag is set to True and stop running when any of several events sets the 
#value of the flag to False."  
while active:
    message = int(input (prompt))

    if int(1) <= message < int(3):
        print("Your ticket is free!")
    elif int(3) <= message <= int(12):
        print("Your ticket is $10!")
    elif message > int(12):
        print("Your ticket is $15!")
    else:
        active = False
        print("\nGoodbye!")

相关问题 更多 >