Gohawks
Gohawks

Reputation: 21

Having user input take string and int? (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")         

This is some fairly simple code but I am having one issue. The problem is, for the code to run age has to be converted into an int. However, the program is also supposed to exit when you type in "quit". You can always have another prompt along the lines of "Would you like to add more people?". However, is there a way to make it run without having to prompt another question?

Upvotes: 0

Views: 52

Answers (2)

Niklas Mertsch
Niklas Mertsch

Reputation: 1489

If you want to add another prompt, you can ask the first prompt before the loop and the other one at the end of it. And if you want to add the prices, you need a variable for it. If you dont want to prompt another question but want more user input, leave the prompt empty.

prompt = "Enter your age for ticket price"
prompt += "\nEnter 'quit' to exit: "
price = 0
user_input = input(prompt)

while True:   
    if user_input == 'quit':
        break
    age = int(user_input)
    if age < 3:
        price += 5
    elif age < 12:
        price += 10
    else:
        price += 15
    print(f"Your ticket is ${price}")
    user_input = input("You can add an age to add another ticket, or enter 'quit' to exit. ")

Upvotes: 0

Phydeaux
Phydeaux

Reputation: 2855

I would suggest getting rid of the active flag, and just breaking when "quit" is entered, like so, then you can safely convert to int, because the code will not reach that point if "quit" was entered:

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")

Note that the age >= 3 and age >= 12 checks are unnecessary, because you have already guaranteed them with the earlier checks.

Upvotes: 1

Related Questions