This question already has answers here:
How to test multiple variables for equality against a single value?
(31 answers)
Closed 2 years ago.
print("Welcome to the Ontario Science Centre! ")
location = int(input("Would you like to attend the Science Centre (1), IMAX Film (2), or both (3)? "))
age = int(input("What is your age? "))
id = input("Do you have a student ID? ('y' or 'n') ")
if location == 1:
if id == 'y':
if age <= 2:
print("Your cost for entry will be $0.00")
elif age <= 17:
print("Your cost for entry will be $13.00")
else:
print("Your cost for entry will be $16.00")
elif id == 'n':
if age >= 65 or >= 13:
print("Your cost for entry will be $16.00")
elif age >= 18:
print("Your cost for entry will be $22.00")
elif age >= 3:
print("Your cost for entry will be $13.00")
else:
print("Your cost for entry will be $0.00")
if location == 2:
if id == 'y':
if age <= 2:
print("Your cost for entry will be $0.00")
else:
print("Your cost for entry will be $9.00")
if id == 'n':
if age <= 2:
print("Your cost for entry will be $0.00")
else:
print("Your cost for entry will be $9.00")
if location == 3:
if id == 'y':
print("Your cost for entry will be $22.00")
elif id == 'n':
if age >= 65 or >= 13:
print("Your cost for entry will be $22.00")
elif age >= 18:
print("Your cost for entry will be $28.00")
elif age >= 3:
print("Your cost for entry will be $19.00")
else:
print("Your cost for entry will be $0.00")
Keep getting this error:
Traceback (most recent call last):
File "python", line 15
if age >= 65 or >= 13:
^
SyntaxError: invalid syntax
I tried everything but i can not see a error.
I am also new to python so Im sorry if the error is easy to spot.
You've to do it like this:
if age >= 65 or age >= 13:
Look how i had to put in the age variable before both numbers.
You should look at it in this way:
that each >= returns either True or False, so if 13 is less or equal to nothing, python don't understand it, and probably aslo many other coding languages.
while the others have answered regarding the syntax, I'm curious whether you really meant age >= 65 or age >= 13 or perhaps age >= 65 or age <= 13?
If you did mean age >= 65 or age >= 13, I think age >= 13 is enough as higher than 65 is also higher than 13.
It must be age >= 65 or age >= 13
Related
I'm getting the following error when I run the following program
File "main.py", line 14
elif age >= 45 and <= 55:
^
SyntaxError: invalid syntax
This is the code that I wrote
print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))
if height >= 120:
print("You can ride the rollercoaster!")
age = int(input("What is your age? "))
if age < 12:
bill = 5
print("Child tickets are $5.")
elif age <= 18:
bill = 7
print("Youth tickets are $7.")
elif age >= 45 and <= 55:
bill = 0
print("Everything is going to be okay! Have a free ride on us <3.")
I was under the impression that this line was written properly
elif age >= 45 and <= 55:
You can use brackets to ensure that there are two statements in one line and they do not conflict with them. Here is my answer. you just need to modify the line or you can copy paste it.
print("Welcome to the rollercoaster!")
height = int(input("What is your height in cm? "))
if height >= 120:
print("You can ride the rollercoaster!")
age = int(input("What is your age? "))
if age < 12:
bill = 5
print("Child tickets are $5.")
elif age <= 18:
bill = 7
print("Youth tickets are $7.")
elif (age >= 45) and (age <= 55):
bill = 0
print("Everything is going to be okay! Have a free ride on us <3.")
Just edit your elif statement from
elif age >=45 and <=55
To
elif age>=45 and age<=55
You should write the conditions completely
In python you can say:
elif 45 >= age <= 55:
pass
This syntax makes your intent clear and is a lot easier to read.
I am trying to get the program to accept an age value, print a response of ticket price, and then return back to the prompt for input to request another age.
Every time I enter an age input I get an infinite loop? How can I approach it differently? Will a continue help?
Apologies for the sloppy formatting etc; it's my first post on stack overflow and I
ticket_age = input("\nTell me your age and I will sell you a ticket")
active = True
while active:
age = int(ticket_age)
if age < 3:
print("You get a free ticket")
elif age >= 3 and age <= 12:
print("That will be $10 please")
elif age > 12:
print("That will be $15 please")
You should use input inside of loop to perform that
while True:
ticket_age = input("\nTell me your age and I will sell you a ticket")
age = int(ticket_age)
if age < 3:
print("You get a free ticket")
elif age >= 3 and age <= 12:
print("That will be $10 please")
elif age > 12:
print("That will be $15 please")
In your program, you should change the value of active variable to false somewhere inside your while loop to break it.
Try this below :
ticket_age = input("\nTell me your age and I will sell you a ticket")
active = True
while active:
age = int(ticket_age)
if age < 3:
print("You get a free ticket")
elif age >= 3 and age <= 12:
print("That will be $10 please")
elif age > 12:
print("That will be $15 please")
else:
break
Welcome! As the comments said, we need more information on what you're tying to do. If it's just a simple check, then you don't even need the while loop. You could just have the if statements alone, or if you want to loop you could loop through multiple inputs. In your case you can exit by setting the active value to false. Otherwise, as a few pointers: in such loops you're using, you do not have to set active = True and then while active:, you can simply do while True:. But you will have to exit it somehow different. You can also directly convert input after receiving it, such as ticket_age = int(input("\nTell me your age and I will sell you a ticket")), or str(input(..)). For your second loop, you can use such syntax: if 3 <= number <= 12:.
So this is what I am struggling with on my assignment...
"You are to account for invalid input. Drivers must be between the ages of 16 and 105. Number of traffic violations cannot be less than 0. Display only the message “Invalid Entry” in either case"
I can get the age part right but for the life of me I cannot get the number of violations to not work... can anyone assist?
Basically what I am needing is I need:
def Invalid_Entry():
if Violation == float or Violation == str and Violation == int:
print("Invalid Entry")
to work... this is my issue. The rest of the code works exactly as it needs to work. However, I need it so when the user enters a number for number of violations it can only be a whole number and a numeric item, no "terms", if that makes sense.
Name = input("What is the customers name? ")
Age = int(input("What is the age of the customer? "))
Violations = int(input("How many violations does the customer have? "))
def main():
Violation = Number_Violations(Violations)
Price = Premium()
Invalid = Invalid_Entry()
if Age < 16 or Age >= 106:
print("Invalid Entry")
else:
print(Name, "as a ", Violation, "risk driver, your insurance will cost
", Price)
def Number_Violations(Violations):
if Violations >= 4:
return "High"
elif Violations == 0:
return "None"
elif Violations == 1:
return "Low"
elif Violations == 2 or 3:
return "Moderate"
else:
Violations != 0
return "invalid Entry"
return Violations
def Premium():
if Violations >= 4 and Age >= 25:
return "$410.00"
elif Violations >= 4 and Age < 25:
return "480.00"
elif Violations == 3 and Age >= 25:
return "390.00"
elif Violations == 3 and Age < 25:
return "450.00"
elif Violations == 2 and Age >= 25:
return "365.00"
elif Violations == 2 and Age < 25:
return "405.00"
elif Violations == 1 and Age >= 25:
return "315.00"
elif Violations == 1 and Age < 25:
return "$380.00"
elif Violations == 0 and Age >= 25:
return "275.00"
else:
return "$325"
def Invalid_Entry():
if Violation == float or Violation == str and Violation == int:
print("Invalid Entry")
main()
You could check both age and number of traffic violations at the beginning of the program, and exit if conditions are not satisfied:
if (Age < 16 or Age >= 106 or Violations<0):
print("Invalid Entry")
exit()
For that solution you will need to import exit function before executing it:
from sys import exit
*EDIT. Following our comments, here is a code that should work:
from sys import exit
Name = input("What is the customers name? ")
# enter age and violations number and check type and value
try:
Age = int(input("What is the age of the customer? "))
Violations = int((input("How many violations does the customer have? ")))
except ValueError:
exit('invalid entry')
if (Violations<0 or Age not in range(16,107)):
exit('invalid entry')
def main(name, age,violations):
driver_risk = Number_violations(violations)
price = Premium(violations,age)
print("{} as a {} risk driver, your insurance will cost {}".format(name, driver_risk, price))
def Number_violations(violations):
if violations == 0:
return "None"
elif violations == 1:
return "Low"
elif violations in [2,3]:
return "Moderate"
else:
return "High"
def Premium(violations,age):
if violations >= 4 and age >= 25:
return "$410.00"
elif violations >= 4 and age < 25:
return "480.00"
elif violations == 3 and age >= 25:
return "390.00"
elif violations == 3 and age < 25:
return "450.00"
elif violations == 2 and age >= 25:
return "365.00"
elif violations == 2 and age < 25:
return "405.00"
elif violations == 1 and age >= 25:
return "315.00"
elif violations == 1 and age < 25:
return "$380.00"
elif violations == 0 and age >= 25:
return "275.00"
else:
return "$325"
main(Name,Age,Violations)
This line of code doesn't do what you expect:
elif Violations == 2 or 3:
It should be this:
elif Violations in [2, 3]:
Teaching myself Python out of a book and I'm stuck on this exercise:
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.
I know how to make it work without using a loop but I am a uncertain how to make it work using a while loop. Any advice or examples would be greatly appreciated.
One way to do this would be an infinite loop. Don't forget to include a break condition, otherwise you won't be able to exit your program gracefully.
while True:
userinput = int(input())
if userinput < 0:
break
# your if logic goes here
I was able to figure it out on my own
prompt = "\nEnter 'quit' when you are finished."
prompt += "\nPlease enter your age: "
while True:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age <= 3:
print("Your ticket is free")
elif age <= 10:
print("Your ticket is $10")
else:
print("Your ticket is $15")
One way of doing it would be creating an infinite loop like such:
price = -1
while price == -1:
try:
age=int(raw_input('Age: '))
except ValueError:
print "Not a number, try again."
continue
if age <= 3:
price = 0
elif age > 3 and age < 12:
price = 10
else:
price = 15
print "The price will be "+str(price)+"$."
Note:
Rename raw_input() to input() if you are using Python 3.
I know this is an old question but none of the answers seemed great. So here's my solution to 7-5/ 7-6
loop = True
#while loop = true run 'while loop'
while loop:
#Print message
print ('Please enter your age.')
#receive input from user
age = raw_input()
#check if the user input "quit" if so end loop. Break ends program but should be replaceable by
#if age == 'quit':
# loop = False
#resulting the the same effect (ending loop)
if age == 'quit':
break
#Convert age input by user to int so it is recognized as a number by python
age = int(age)
#If/ elif pretty self explanatory
if age < 3:
price = 5
elif age < 12:
price = 10
elif age > 12:
price = 15
else:
print('Input not recognized')
break
#Print ticket price based on age and ask user if they need another price/inform them how to exit program
print('Your ticked price is $' + str(price) + '.')
print('\n If you would like to check the price for another person please enter their age now or type "quit" to exit')
The formatting might be a little off since it pasted oddly. I tried to explain what everything does. Also I use 2.7 instead of 3 so if you're using python 3 replace raw_input() with input()
Hopefully this answer was helpful to some on. GL with programming.
prompt = "How old are you? "
prompt += "\nEnter 'quit' when you are finished. "
while True:
age = input(prompt)
if age == 'quit':
break
age = int(age)
if age < 3:
print("Your ticket is free. Congratulations")
elif age < 13:
print("Your ticket is $10 dollars")
else:
print("Your ticket is $15 dollars")
prompt = "\nPlease enter 'done' when finished! "
prompt += "\nPlease enter your age:"
while True:
try:
age = input(prompt)
if age == 'done':
break
age = int(age)
if age <= 3:
print("Free ticket")
elif age in range(4, 12):
print("You must pay 10$")
elif age >= 12:
print("You must pay 15$")
except ValueError:
continue
I am trying to do two things here.
I want to print "value entered is not a valid age" if the input is not a number in this code:
age = float(input (' enter your age: '))
if 0 <age < 16:
print "too early for you to drive"
if 120 >= age >= 95:
print 'Sorry; you cant risk driving'
if age <= 0:
print 'Sorry,' ,age, 'is not a valid age'
if age > 120:
print 'There is no way you are this old. If so, what is your secret?'
if 95 > age >= 16:
print 'You are good to drive!'
Also, how can I repeat this program once it is done?
You could check whether input is a valid digit with isdigit method of str. For multiple times you could wrap your code to a function and call it as much as you want:
def func():
age = input (' enter your age: ')
if age.isdigit():
age = float(age)
if 0 <age < 16:
print "too early for you to drive"
if 120 >= age >= 95:
print 'Sorry; you cant risk driving'
if age <= 0:
print 'Sorry,' ,age, 'is not a valid age'
if age > 120:
print 'There is no way you are this old. If so, what is your secret?'
if 95 > age >= 16:
print 'You are good to drive!'
else:
print "value entered is not a valid age"
func()
For make this code runnig every time you should add a loop , like while loop , and add a break whenever you want end this loop or add a condition for example run 10 times,and if you want check the input is float , you can add a try section:
counter = 0
while counter < 10:
age = raw_input (' enter your age: ')
try :
age = float(age)
if 0 <age < 16:
print "too early for you to drive"
if 120 >= age >= 95:
print 'Sorry; you cant risk driving'
if age <= 0:
print 'Sorry,' ,age, 'is not a valid age'
if age > 120:
print 'There is no way you are this old. If so, what is your secret?'
if 95 > age >= 16:
print 'You are good to drive!'
counter -= 1
except ValueError:
print "value entered is not a valid age"
It is also a good idea to arrange your cases in order, to make it easier to see what is happening (and to make sure you didn't leave an unhandled gap):
while True:
age = input("Enter your age (or just hit Enter to quit): ").strip()
if not age:
print("Goodbye!")
break # exit the while loop
try:
# convert to int
age = int(age)
except ValueError:
# not an int!
print("Value entered is not a valid age")
continue # start the while loop again
if age < 0:
print("Sorry, {} is not a valid age.".format(age))
elif age < 16:
print("You are too young to drive!")
elif age < 95:
print("You are good to drive!")
elif age <= 120:
print("Sorry, you can't risk driving!")
else:
print("What are you, a tree?")