I'm doing my first project with Python and I was trying to do it without help, but I don't understand why is this not working.
I want to ask the user their age. If the user is older than 15, then he/she can play; if they're younger than 16 then I want to ask again for the age until the user says they're older than 15.
It works for when the user is less than 16, but if I type, say, 18, it still asks again.
while True:
age = int(input('Please introduce your age: '))
if age >= 15:
character_info['age'] = age
print('You are old enough to play')
elif age <= 16:
print('You are not old enough to play. Try again')
age = int(input('Please introduce your age: '))
continue
You need to break when the correct condition is met.
The correct logic is as follows
while True:
age = int(input('Please introduce your age: '))
if age >= 15:
character_info['age'] = age
print('You are old enough to play')
break
elif age <= 16:
print('You are not old enough to play. Try again')
Related
I am working on a simple python exercise where I ask a series of questions and get input from the user. I prompt the user with "Enter your age" and I want the program to continue rather than be corrupt if the user enters a letter value for the age rather than int because I am converting to int to figure if the age is less than 18 or greater than and if it is between specific ages. I can't convert letters to an int.
age = input("Please enter your age: ")
if int(age) < 18 or int(age) > 120:
print("We're sorry, you are not old enough to be qualified for our program. We hope to see you in the future.")
end()
if int(age) > 18 and int(age) < 120:
print("You are " + age + "years old.")
if int(age) > 120:
print("You are not qualified for this program. ")
end()
#Somewhere in this script I am hoping to accept the letter input without sending an error to the program.
Use try/except.
age = input("Please enter your age: ")
try:
if int(age) < 18 or int(age) > 120:
print("We're sorry, you are not old enough to be qualified for our program. We hope to see you in the future.")
end()
if int(age) > 18 and int(age) < 120:
print("You are " + age + "years old.")
if int(age) > 120:
print("You are not qualified for this program. ")
end()
except:
print("Please enter a number")
If your int conversion fails the code will jump to except instead of crashing.
If you want the user to retry, you could write something like this instead. Be aware of the ranges you're using and negative numbers.
age = input("Please enter your age: ")
ageNum = 0
while(ageNum <= 0):
try:
ageNum = int(age)
if (ageNum) < 18 or ageNum > 120:
print("We're sorry, you are not old enough to be qualified for our program. We hope to see you in the future.")
end()
elif ...
except:
print("Please enter a valid number")
I'd use a while loop, e.g.
while int(age) != age:
input("Age must be an integer.\nPlease try again.")
And as #Barmar stated, you need to check your if statements.
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:.
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.
My code so far:
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")
The program runs fine unless you enter 'quit' to end the loop. I understand that age = int(age) defines the user input as an integer. My question is how can I change it to to not treat 'quit' as an integer and end the loop when 'quit' is input.
If age is 'quit', you will break anyway. Therefore, you can just use if for the next one instead. As long as you do that anyway, you can make it an int after that if:
while True:
age = input(prompt)
if age == 'quit':
break
age = int(age)
if age <= 3:
print("Your ticket is free")
elif age <= 10:
print("Your ticket is $10")
else:
print("Your ticket is $15")
You should probably take care of those cases when the user types something else, however, so I would suggest the following:
while True:
age = input(prompt)
if age == 'quit':
break
elif not age.isdigit():
print("invalid input")
continue
age = int(age)
if age <= 3:
print("Your ticket is free")
elif age <= 10:
print("Your ticket is $10")
else:
print("Your ticket is $15")
I would introduce a try/except here, actually.
The main goal of your application is to gather ages. So, wrap your input with a try/except to always get an integer. If you get a ValueError, you fall in to your exception block and check to see if you entered quit.
The application will tell the user it is quitting and break out. However, if the user did not enter quit, but some other string, you are told that the entry is invalid, and it will continue to ask the user for a valid age.
Also, just to make sure you never miss a 'quit' message that could be typed with different cases, you can always set the input to lower to always compare the same casing in your string. In other words, do age.lower when you are checking for the entry to be quit.
Here is a working demo:
prompt = "\nEnter 'quit' when you are finished."
prompt += "\nPlease enter your age: "
while True:
age = input(prompt)
try:
age = int(age)
except ValueError:
if age.lower() == 'quit':
print("Quitting your application")
break
else:
print("You made an invalid entry")
continue
if age <= 3:
print("Your ticket is free")
elif age <= 10:
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