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.
Related
def GetAge():
age = int(input("Please enter your age: "))
return age
def DetermineAge():
if age < 2:
print("Stage of Life: A Baby")
elif age < 4:
print("Stage of Life: A Toddler")
elif age < 13:
print("Stage of Life: A Kid")
elif age < 20:
print("Stage of Life: A Teenager")
elif age < 65:
print("Stage of Life: An Adult")
elif age >= 65:
print("Stage of Life: An Elder")
else:
print("Mistakes were made, please restart the program and try again.")
age = GetAge()
DetermineAge()
Trying to remove age out of age = GetAge how do I do that with my function? I already define age in my function and return it I only want my main code to say GetAge() and DetermineAge()
Change DetermineAge to take age as an argument:
def DetermineAge(age):
# rest of function is the same
and then the caller can pass the value as an argument directly instead of needing the variable age to be defined in the caller's own scope:
DetermineAge(GetAge())
Alternatively, you could have DetermineAge call GetAge() itself:
def DetermineAge():
age = GetAge()
# rest of function is the same
and then the caller can just do:
DetermineAge()
If you wanted the function itself to be an argument, you could also do that:
def DetermineAge(get_age_func):
age = get_age_func()
# rest of function is the same
DetermineAge(GetAge)
You can use a decorator function that takes a function as an argument and calls it with #, like this
def DetermineAge(func):
def wrapper(*args, **kwargs):
age = func(*args, **kwargs)
if age < 2:
print("Stage of Life: A Baby")
elif age < 4:
print("Stage of Life: A Toddler")
elif age < 13:
print("Stage of Life: A Kid")
elif age < 20:
print("Stage of Life: A Teenager")
elif age < 65:
print("Stage of Life: An Adult")
elif age >= 65:
print("Stage of Life: An Elder")
else:
print("Mistakes were made, please restart the program and try again.")
return age
return wrapper
#DetermineAge
def GetAge():
age = int(input("Please enter your age: "))
return age
age = GetAge()
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
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]:
I am new to coding in Python. I am trying to make my code so that if I enter the age a series of text will be printed. However, my code only works if i follow it line by line. For example, when i input the age 2000+ immediately nothing will happen. I need to first input an integer less than 12, followed by an integer over 2000.
print('Please input name')
if input() == 'Alice':
print('Hi, Alice.Please input age')
if int(input()) < 12:
print('You are not Alice, kiddo.')
elif int(input()) > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif int(input()) == 100:
print('You are not Alice, grannie.')
elif 12 < int(input()) < 99:
print('You are Alice!.')
var = input('Please input name ')
if var == 'Alice':
var = int(input('Hi, Alice.Please input age '))
if var < 12:
print('You are not Alice, kiddo.')
elif var > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif var == 100:
print('You are not Alice, grannie.')
elif 12 < var < 99:
print('You are Alice!.')
else:
print ("Invalid Name")
This code works because it asks one time and tries to see if some conditions are true, instead of asking each time.
Here I wrote code for your understanding purpose. Take new variable, so that no need to repeat input() method several times. Also, Age validation code keeps inside the first condition and it will be executed when the 1st condition will be true.
print('Please input name')
var = input()
if var == 'Alice':
print('Hi, Alice.Please input age')
var = input()
try:
if int(var) < 12:
print('You are not Alice, kiddo.')
elif int(var) > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif int(var) == 100:
print('You are not Alice, grannie.')
elif 12 < int(var) < 99:
print('You are Alice!.')
except Exception as ex:
print('Invalid Data: Error: ' + ex)
else:
print ("Invalid Name")
Every time you go to another branch in you if you are asking user to enter another age! Instead do the following:
age = int(input())
if age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif age == 100:
print('You are not Alice, grannie.')
elif 12 < age < 99:
print('You are Alice!.')
print('Please input name')
if input() == 'Alice':
print('Hi, Alice.Please input age')
age = int(input()) # take input and assign it on a variable
if age < 12:
print('You are not Alice, kiddo.')
elif age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
elif age == 100:
print('You are not Alice, grannie.')
elif 12 < age < 99:
print('You are Alice!.')
input is invoked every time when followed by (). So the multiple input()'s in the if elif's are not necessary.
store the result of input() like age = int(input()), then use age in the if and elif parts instead.
The input() function returns a string. Quoting the docs (emphasis mine):
The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that.
So, in each if when you call input(), you have to enter a new string. Thus, you have to first enter an integer below 12.
To fix this problem, you need to store the original input in a variable. Now, as the docs say, input() returns a string. So, either you can cast (using int()) the integer in each case, by doing:
if int(age) < 12:
and storing the variable as a string.
Though, unless you do not have any specific reason to keep the age as a string, I'd recommend you to convert the string while storing the age in the variable in the first place:
age = int (input())
In this case, age will have an int.
Hopefully, this is what you are looking for:
while True:
name = input("Please ENTER your name: ")
if name == "Alice":
print("Hi Alice!")
break
print("Sorry, your name isn't correct. Please re-enter.")
age = False
while age != True:
age = int(input("Please ENTER your age: ")
age = True
if age < 12:
print("You're not Alice, kiddo.")
age = False
elif age > 2000:
print("Unlike you, Alice is not an undead, immortal vampire.")
age = False
elif age == 100:
print("You're not Alice, Granny!")
age = False
else:
print("You are Alice!")
age = True
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?")