让用户输入接受字符串和整数?(Python)

 prompt = "Enter your age for ticket price"

prompt += "\nEnter quit to exit: "


active = True


while active:   

    age = input(prompt)

    age = int(age)

    if age == 'quit':

        active = False

    elif age < 3:

        print("Your ticket is $5")

    elif age >= 3 and age < 12:

        print("Your ticket is $10")

    elif age >= 12:

        print("Your ticket is $15")         

这是一些相当简单的代码,但我遇到了一个问题。问题是,要运行的代码 age 必须转换为 int。但是,当您输入“quit”时,程序也应该退出。你总是可以有另一个提示,比如“你想添加更多人吗?”。但是,有没有办法让它运行而不必提示另一个问题?


www说
浏览 147回答 2
2回答

肥皂起泡泡

我建议去掉active标志,只break在"quit"输入时 ing ,像这样,然后你可以安全地转换为int,因为如果"quit"输入代码将不会到达那个点:while True:&nbsp; &nbsp;&nbsp; &nbsp; age = input(prompt)&nbsp; &nbsp; if age == "quit":&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; age = int(age)&nbsp; &nbsp; if age < 3:&nbsp; &nbsp; &nbsp; &nbsp; print("Your ticket is $5")&nbsp; &nbsp; elif age < 12:&nbsp; &nbsp; &nbsp; &nbsp; print("Your ticket is $10")&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; print("Your ticket is $15")请注意,age >= 3和age >= 12检查是不必要的,因为您已经使用较早的检查保证了它们。

开满天机

如果您想添加另一个提示,您可以在循环之前询问第一个提示,并在循环结束时询问另一个提示。如果你想添加价格,你需要一个变量。如果您不想提示其他问题但想要更多用户输入,请将提示留空。prompt = "Enter your age for ticket price"prompt += "\nEnter 'quit' to exit: "price = 0user_input = input(prompt)while True:&nbsp; &nbsp;&nbsp; &nbsp; if user_input == 'quit':&nbsp; &nbsp; &nbsp; &nbsp; break&nbsp; &nbsp; age = int(user_input)&nbsp; &nbsp; if age < 3:&nbsp; &nbsp; &nbsp; &nbsp; price += 5&nbsp; &nbsp; elif age < 12:&nbsp; &nbsp; &nbsp; &nbsp; price += 10&nbsp; &nbsp; else:&nbsp; &nbsp; &nbsp; &nbsp; price += 15&nbsp; &nbsp; print(f"Your ticket is ${price}")&nbsp; &nbsp; user_input = input("You can add an age to add another ticket, or enter 'quit' to exit.
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python