首页 > 解决方案 > 让用户输入采用字符串和整数?(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")         

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

标签: python

解决方案


我建议去掉该active标志,并在break输入时"quit"输入,就像这样,然后您可以安全地转换为int,因为如果输入代码将不会到达该点"quit"

while True:   
    age = input(prompt)

    if age == "quit":
        break

    age = int(age)
    if age < 3:
        print("Your ticket is $5")
    elif age < 12:
        print("Your ticket is $10")
    else:
        print("Your ticket is $15")

请注意,age >= 3andage >= 12检查是不必要的,因为您已经用早期的检查保证了它们。


推荐阅读