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
Related
print('Hi there, what is your name')
name = input()
if name == 'Alice':
print('Hello, Alice')
if name != 'Alice':
print('how old are you?')
age = int(input())
elif 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.')
When I run the program I get
Hi there, what is your name
Jeff
how old are you?
5
Process finished with exit code 0
The reason for that is you using elif instead of if. If you use if and elif combination, it'll always execute in that order and the first caught condition will capture the whole execution.
For example:
if name == 'Alice':
print('how old are you?')
age = int(input())
elif name == "Alice" and True:
print("won't be executed")
For you to fix it you can either nest the conditions via:
if name == "Alice":
if age == 123:
do_stuff()
which is the same as:
if name == "Alice" and age == 123:
do_stuff()
or you can edit your condition tree (if you want to continue the code flow) to ifs instead and catch each of the cases individually:
print('Hi there, what is your name')
name = input()
if name == 'Alice':
print('Hello, Alice')
if name != 'Alice':
print('how old are you?')
age = int(input())
if name == "Alice" and age < 12:
print('You are not Alice Kiddo.')
if name == "Alice" and age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
if age > 100:
print(f'You are not Alice, Grannie, but you might be {name}')
if name == "Bob":
print("Hi Bob")
this will work for you
print('Hi there, what is your name')
name = input()
if name == 'Alice':
print('Hello, Alice')
if name != 'Alice':
print('how old are you?')
age = int(input())
if age < 12:
print('You are not Alice Kiddo.')
if age > 2000:
print('Unlike you, Alice is not an undead, immortal vampire.')
if age > 100:
print('You are not Alice, Grannie.')
The problem is with the elif statements, they are used if the if statement is not true
They are like "else if", or "if not, then"
for example:
a = input("Enter 1 or 2")
if a == 1:
print("Why didn't you input two?")
elif a == 2:
print("Why didn't you input one?")
First a little about the program itself:
A conditional test begins the while loop (I have to use a conditional test to begin and end the loop, No flags and no break statements)
Asks for users age (user input)
Depending on the user input, it prints out different answers
My problem is that I want the program to end if the user input is 'quit'. The user input will besides 'quit' always be an int, because the program checks the users age.
This is my code:
prompt = "\nPlease enter your age to see the price for a ticket. \nEnter 'quit' when done: "
age = ""
while age != "quit":
age = input(prompt)
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age > 3 and age < 12:
print("Ticket is $10")
else:
print("Ticket is $15")
This is the error i get when i put 'quit' as the input:
Please enter your age to see the price for a ticket. Enter 'quit' when done: quit
Traceback (most recent call last): File "while_loops.py", line 60, in <module>
age = int(age) ValueError: invalid literal for int() with base 10: 'quit'
Many thanks in advance for your time and effort! Best regards HWG.
Check for quit before you try to convert to int. Run in an infinite loop and break out of it when you read the input quit.
prompt = "\nPlease enter your age to see the price for a ticket. \nEnter 'quit' when done: "
while True:
age = input(prompt)
if age == "quit":
break
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age > 3 and age < 12:
print("Ticket is $10")
else:
print("Ticket is $15")
Alternative which meet added criteria
not use 'break' or a variable as a flag
Using an exception
while ageStr != "quit":
ageStr = input(prompt)
try:
age = int(ageStr)
if age < 3:
print("Your ticket is free.")
elif age > 3 and age < 12:
print("Ticket is $10")
else:
print("Ticket is $15")
except ValueError:
pass
Using continue.
Note: this is bad as you specify and check for "quit" twice in the code and the control flow is overly complicated.
prompt = "\nPlease enter your age to see the price for a ticket. \nEnter 'quit' when done: "
age = ""
while age != "quit":
age = input(prompt)
if age == "quit":
continue
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age > 3 and age < 12:
print("Ticket is $10")
else:
print("Ticket is $15")
while True:
age = input("\nPlease enter your age to see the price for a ticket. \n Enter 'quit' when done: '"
if age == 'quit':
break
# continue with the rest of your code
Just check to see if the input is 'quit', if so, break out of the infinite loop.
This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 6 years ago.
I'm going through the book Python Crash Course and ran into a little hiccup on one of the exercises. Basically it asks you to create a while loop that tells the user to input their age and it will return the price of a ticket based on their age. This is supposed to repeat until the user types 'quit'. Pretty simple, except I'm confused as to how I would go from converting the input from an integer (their age) to a string ("quit"). I get the error: "invalid literal for int() with base 10: 'quit'" whenever I try to type quit. This is what I have so far:
age_prompt = "\nWrite in your age: "
age_prompt += "\nType 'quit' to exit "
while True:
age = int(input(age_prompt))
if age < 3:
print("Your ticket is free.")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
if age == 'quit':
break
You would need to test if the variable was "quit" before converting to an integer (because "quit" obviously isn't a number, so Python rightly complains).
Here's how you could do it:
while True:
age = input(age_prompt)
if age == 'quit':
break
try:
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
except ValueError:
print("Invalid input. Please enter a valid number or 'quit'")
age_prompt = "\nWrite in your age: "
age_prompt += "\nType 'quit' to exit "
while True:
try:
age = input(age_prompt)
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
except ValueError:
if age == 'quit':
break
Check to see if it is an int. If not, check if it is 'quit'
User input is received as a string from the call to input(). In your example, you are directly converting the output of input() into an integer:
age = int(input(age_prompt))
Once you have converted the input to an integer, you can no longer compare the integer to the string "quit" as they are not directly comparable. You can process the input string before converting to an integer.
# read user input as a string
user_input = input(age_prompt)
if user_input == "quit":
quit()
elif user_input == SOME_OTHER_COMMAND:
other_command()
else:
# try to convert input into an integer
try:
age = int(user_input)
except ValueError:
print "Input '%s' is invalid!"
quit()
if age < 3:
...
Try this:
age_prompt = "\nWrite in your age: "
age_prompt += "\nType 'quit' to exit "
while True:
age = raw_input(age_prompt)
if age == 'quit':
break
else:
age = int(age)
if age < 3:
print("Your ticket is free.")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
you would have to use seperate variables (or exceptions - without example)
while True:
ui = input(age_prompt)
if ui == 'quit':
break
age = int(ui)
if age < 3:
print("Your ticket is free.")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
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?")