Question: “A movie theater charges different ticket prices depending on a person’s age. If a person is under the age of 3, the ticket is free; if they are between 3 and 12, the ticket is $10; and if they are over age 12, the ticket is $15. Write a loop in which you ask users their age, and then tell them the cost of their movie ticket.”
The reason I put != 'quit' is to give the end user the option of quiting the program. I don't know if that makes sense. This is what I have so far:
prompt = 'What is your age? '
age = ' '
while age != 'quit':
age = input(prompt)
age = int(age)
if age < 3:
price = 0
if age > 3:
price = 10
if age < 12:
price = 15
print('The price of your ticket is ' + price)
I keep getting a syntax error on the last print statement.
Preamble: In general, you should write what your code is supposed to accomplish. Also, it would be helpful if you wrote your code in a .py file for my (and anyone else who wants to help) convenience; I can't paste your code in the python interpreter, so I have to paste it in a file but I have to remove all those ">>>" and "...".
In this case, I will deduce that your requirements are
Get an age from the user and print it.
Validate the input and continue asking for an age until the input is valid.
The problem that you have is that your condition for quitting causes problem:
~/Desktop $ python3 stack_overflow.py
What is your age? 32
Age : 32
What is your age? quit
Age : quit
Traceback (most recent call last):
File "stack_overflow.py", line 6, in <module>
age = int(age)
ValueError: invalid literal for int() with base 10: 'quit'
So let's get the logic that we want down, then we'll see how to do it in python.
<get a valid input>
<decide the ticket price based on said valid input>
One thing to note is that in python, since the input is valid if it can be turned into an int we can try to turn it into an int and call the input valid if that conversion succeeds.
By reading error messages we can see that writing 'quit' results in ValueError, we can deduce that this:
prompt = 'What is your age? '
age = ' '
input_valid = False
while !input_valid:
age = input(prompt)
try:
age = int(age)
except ValueError:
input_valid = False
continue
if age > 0:
break
if age < 3:
price = 0
if age > 3:
price = 10
if age < 12:
price = 15
print('The price of your ticket is ' + str(price))
Now, at this point, I think you would have satisfied your requirements. However, lemme drop some more knowledge on you:
What if you read the following code:
age = get_age()
price = ticket_price(age)
print("The price of your ticked is " + str(age))
This reminds me of something I saw in a talk on YouTube which I thought was really nice: write code using functions that you wish existed then implement those functions.
def get_age():
while True:
age = input('What is your age : ')
try:
age = int(age)
except ValueError:
continue
if age > 0:
return age
def ticket_price(age):
if age < 3:
# Under 3 years old don't pay
return 0
if age < 12:
# between 3 and 12, price is 10$
return 10
# 12 and above pay 15
return 15
age = get_age()
price = ticket_price(age)
print('The price of your ticket is ' + str(price))
Also, another tip: whenever I have something like
while True:
...
if <something>:
break
It's a good idea to put that while loop in a function and replace the break with a return statement.
Given that I did not have your requirements, I can't be sure I solved your question. That being said, the main takeaways should be
separating the getting of input and the conversion from age to
price.
putting code into functions is worth your time even for toy examples
like this because it's practice for actual coding.
Writing out the logic of your program in pseudo code is also helpful.
You need to change the way you have set up your loop. It shouldn't terminate if the user enters 'quit' as the age. This doesn't make sense for the rest of your logic with regards to the variable age. Instead of using a while loop, you could instead use a for loop and print the price for a number of users
for user in range(5):
age = int(input('What is your age?'))
if age < 3: price = 0
if 3 <= age <= 12: price = 10
if age > 12: price = 15
print('The price of your ticket is: $' + str(price))
Related
Here is the actual code
age = input('How old are you? ')
# 2-8 2 dollar ticket
# 65 5 dollar ticket
# 10 dollar for everyone else
if not ((age >= 2 and age <= 8) or age >= 65):
print('You are not a child, you pay full price')
else:
print('You are paying a discounted price')
Just learning to code but I did something similar and had the same code error, then I copied the one from the online course I am taking and got the same error.
You are trying to compare a string with an integer. You need to convert the string to an integer first:
age = int(input('How old are you? '))
To make sure the user inputs an integer, you can use this.
age = input('How old are you? ')
while not age.isdigit():
age = input('Enter an integer. How old are you? ')
age = int(age)
when convertin to int object, exceptions may be raised by the program so use the try except (if you need to print some message before exiting the program).
age = input('How old are you? ')
try:
age=int(age)
except ValueError:
print('only numbers is alowed! please re run the program')
raise
# 2-8 2 dollar ticket
# 65 5 dollar ticket
# 10 dollar for everyone else
if not ((age >= 2 and age <= 8) or age >= 65):
print('You are not a child, you pay full price')
else:
print('You are paying a discounted price')
This will help you:
age = input('How old are you?')
# 2-8 2 dollar ticket
# 65 5 dollar ticket
# 10 dollar for everyone else
if not ((int(age) >= 2 and int(age) <= 8) or int(age) >= 65):
print('You are not a child, you pay full price')
else:
print('You are paying a discounted price')
I am trying to write a program that determines a person stage of life, whether the person is a baby, kid, teenager, adult or elder. The program starts with a variable that contains an input() function that allows the user to type in an age so the program can start running.
The issue is that when I type ages higher than 99, the program prompts that the person whose age has been typed in is a baby. So basically, according to the program someone who is 123 years old is a baby, which does not make sense.
age=input("enter the person's age: ")
if age<'2':
print('the person is a baby')
elif age=='2' and age<'4':
print('the person is a toddler')
elif age >='4' and age<'13':
print ('the person is a kid')
elif age>='13' and age<'20':
print('the person is a teenager')
elif age>='20' and age<'65':
print('the person is an adult')
elif age>='65':
print('the person is an elder')
I am wondering if I am making a mistake on my code, although it seems to me pretty straight forward. Anyways, I am guessing there is some theoretical knowledge that I am missing, if that is the case I would appreciate if you folks can shed some light on the whole issue.
What you are essentially doing here is comparing strings which does not translate to the behavior you are seeking. You will need to cast the input as int() first.
If you know the input is guaranteed to be formatted correctly, use:
age = int(input("enter the person's age: "))
However, nobody is perfect so it would be best to wrap in a try-except:
age = input("enter the person's age: ")
try:
age = int(age)
except:
# Handle exception
if age < 2:
# Do something
elif ...
# Do more stuff
You are comparing strings no integers thus '100' is less than '99' as the first and second characters are less.
You need to convert your input to an integer and thenuuse that for the comparisons and then you shall be fine.
You should convert age to an integer and then compare. You are comparing strings, and that gives you weird answers.
Reformatted code:
age_str=input("enter the person's age: ")
try:
age = int(age_str)
except:
print("Invalid Entry. Enter age as a number.")
exit(0)
if age < 2:
print('the person is a baby')
elif age == 2 and age < 4:
print('the person is a toddler')
elif age >= 4 and age < 13:
print('the person is a kid')
elif age >= 13 and age < 20:
print('the person is a teenage r')
elif age >= 20 and age < 65:
print('the person is an adult')
elif age >= 65:
print('the person is an elder')
Code also checks for invalid entries above. If anything other than an integer is entered, it throws an error.
This question already has answers here:
How can I read inputs as numbers?
(10 answers)
Closed 6 years ago.
So I have the following function in my script:
def age():
global age
age = raw_input("Age: ")
if age == 14:
sleep(1)
print ("LOL, same")
elif age < 18:
sleep(1)
print ("This test is made for contestants older than ten")
introduction()
elif age > 18:
sleep(1)
print ("Geez grandpa, you sure are old")
When I run this, it registers every age I type as above 18 like so:
Could you tell me your age?
Age: 4
Geez grandpa, you sure are old
Why does it do this?
As raw_input returns the user input as a string type, you should cast it into int.
Change this :
age = raw_input("Age: ")
To:
age = int(raw_input("Age: "))
your raw_input is taken as string
age = raw_input("Age: ")
so you need to convert it into a integer value if you want to compare it against numbers..
age = int(raw_input("Age: "))
I was requested by my teacher to write a program in python which would require visitors of said attraction to insert the number of family members they are visiting with, and based off of that, have them know the admission fee. The admission fees given were $25 for anybody under 16, and 40 for anybody over 40.
This is what I've got so far:
def main():
admission = 0
print("Welcome to Wally World - use this program to calculate your admission fees")
number = int(input("How many members will you be taking with you? "))
members = {}
for n in range(0,number):
age = int(input("Please enter your ages: "))
if age <= 16:
admission = 25
if age > 16:
admission = 40
main()
How would I go about grabbing said admission values and adding them all together?
Thank you!
There is no need to use members = {}
Admissions can be added with only single line conditional statement (ternary if-else).
Check whether number of person is not negative or zero (I've used exit() in this case).
Check whether age is not negative (I've put pass you may call your program again using main() or exit using exit()).
Here is the working code:
def main():
admission = 0
print("Welcome to Wally World - use this program to calculate your admission fees")
number = int(input("How many members will you be taking with you? "))
if number < 0: exit()
for n in range(0,number):
age = int(input("Please enter your ages: "))
admission += (25 if age <= 16 and age > -1 else 40 if age> 16 else 0)
return admission
main()
Purpose is to put diff ages in, if -1 is entered then the program stops, my totaling statement is wrong. Will Someone please help me fix it.
Totalage = 0
age = 0
print "Enter you Family member's ages!"
age = raw_input ("Enter an age ")
while age != -1:
age = input("Enter an age ")
Totalage = Totalage + age
print Totalage
There are two problems with your code
You are skipping your first input, and you are not adding it to your total
You are adding the last terminator input -1 to your Total.
Just Change the order of the statements in your while loop
age = int(raw_input ("Enter an age "))
while age != -1:
Totalage = Totalage + age
age = int(input("Enter an age "))
Also note, raw_input, in general returns a string, which needs to be converted to int before you may want to calculate on it.
Itertools Provide some wonderful tools, and for fun, I tried coding the above while loop with itertools.takewhile
>>> from itertools import count, takewhile
>>> sum(takewhile(lambda x: x != -1,
(int(raw_input("Enter an age ")) for e in count())))
Enter an age 20
Enter an age 30
Enter an age 40
Enter an age 50
Enter an age -1
140
The problem is that your while condition is working properly, but you don't trigger it until your next run through. Therefore if your input is -1, this:
age = input("Enter an age ")
Totalage = Totalage + age
Will decrement the age by -1 and on the next loop through it will exit the loop. In order to adjust, you could do something like this. Note that one adjustment is changing input to raw_input (usually a better practice in Python 2.x, and Python 3.x changes the behavior of input to match it):
Totalage = 0
print "Enter you Family member's ages!"
while True:
age = int(raw_input("Enter an age "))
if age == -1:
break
Totalage += age
print Totalage
while True puts you into a continuous loop, and you break out of it whenever the value -1 is entered. Also, the int here is what you need to do to convert the number to an integer. This will fail if somebody enters an incorrect value (like 'ten', for instance), so if that is a concern you would have to add some additional error handling.
The problem is that you're adding -1 to Totalage before the loop condition is checked. You could rewrite the loop something like this instead:
print "Enter you Family member's ages!"
Totalage = 0
while True:
age = input("Enter an age ")
if age == -1:
break
Totalage += age
print Totalage