0

So I have this loop figured out but with values over 10, the program double prints how much the ticket cost. What is wrong with my code?

age = input("Enter your age to get ticket prices: ")


for ages in age:
    ages = int(age)
    if ages < 3:
        print("Your ticket is free!")
    if 3 <= ages <= 12:
     print("Your ticket is $10")
    if ages > 12:
        print("Your ticket is $15")

I was only expecting a single print of whatever print() statement I have set.

Daniel Walker
  • 6,380
  • 5
  • 22
  • 45
  • 2
    The type of `age` is `str`, so the for-loop will loop over each character that you input into `age` and then translate that character into an integer. If you give it a larger number, say 100, then it will do the same thing, but thrice instead. – Hampus Larsson Mar 06 '23 at 19:59
  • @HampusLarsson How can I prevent this from happening? – Rylan-Ferrer Mar 06 '23 at 20:02
  • 3
    @Rylan-Ferrer, what are you trying to loop over? – Daniel Walker Mar 06 '23 at 20:03
  • just do age =int( input("Enter your age to get ticket prices: ")) – momo123321 Mar 06 '23 at 20:09
  • and u elif and else. not only if's – momo123321 Mar 06 '23 at 20:10
  • @user20194358 Yup this solved it. But what the difference between using input() and int() separately and together? – Rylan-Ferrer Mar 06 '23 at 20:20
  • @Rylan-Ferrer the function `input("your text here")` in Python(3.x) returns a string, which means that even if you give it a number, the type of that number will still be a string. The function `int()` takes either a string, or a number, and tries to translate that into a number (integer). So calling `int(input("your text here"))` will basically try to cast whatever you input there into an integer immediately. There is no difference between doing that in one line, or doing it on separate lines however, it can sometimes be more convenient to do it on separate lines, sometimes not. – Hampus Larsson Mar 06 '23 at 20:26

1 Answers1

0

You can convert input to integer like age = int(input("Enter your age to get ticket prices: ")) and catch the error if it's anything else but a number. You don't really need loop in your case because you check if one number is over or under certain conditions