How to use a conditional test to exit a while loop? - python

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.

Related

How to accept String letter Input from int conversion in Python?

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 new to python with no previous coding experience. My program is supposed to display the price of a ticket depending on age. Why does it not work?

My code will display ticket price dependent on age. Why is it not working? This is exercise 7-5 from the Python Crash Course book.
prompt = "\nEnter Age: "
prompt += "\nEnter 'quit' when done."
age = ''
while age != 'quit':
age = input(prompt)
print(age)
if age != 'quit':
if age > '13':
print(f'You ticket price is $15.00.')
print(f'Retrieve your ticket(s) below')
if age <= '13' and age > '2':
print(f'Your ticket price is $10.00.')
print(f'Retrieve your ticket(s) below')
if age < '3':
print(f'Your ticket price is free')
print(f'Retrieve your ticket below')
print(f'Thank You Enjoy the show')
For starters, you need to cast your input to an int. Input reads everything in as a string.
age = int(input(prompt))
This would also mean you need to change
age != 'quit'
After that, you need to make sure you are comparing int's not strings. A string can be greater than or less than another string, but not in the context that you are using them. Change '13' to 13 and so forth.
You must convert your input value to an integer before using comparators
lower() means you're converting it to lower chars
strip() means you're removing spaces surrounding the text
prompt = ''
while prompt.lower().strip() != 'quit':
prompt = input("Enter your age (enter 'quit' to exit) : ")
if prompt.lower().strip() != 'quit':
age = int(prompt) # Converting prompt to an integer
print(f"Your age : {age}")
if age > 13:
print(f'You ticket price is $15.00.')
print(f'Retrieve your ticket(s) below\n')
if age <= 13 and age >= 3:
print(f'Your ticket price is $10.00.')
print(f'Retrieve your ticket(s) below\n')
if age < 3:
print(f'Your ticket price is free')
print(f'Retrieve your ticket below\n')
print(f'Thank You Enjoy the show')
Here is the result :
Enter your age (enter 'quit' to exit) : 2
Your age : 2
Your ticket price is free
Retrieve your ticket below
Enter your age (enter 'quit' to exit) : 3
Your age : 3
Your ticket price is $10.00.
Retrieve your ticket(s) below
Enter your age (enter 'quit' to exit) : 13
Your age : 13
Your ticket price is $10.00.
Retrieve your ticket(s) below
Enter your age (enter 'quit' to exit) : 16
Your age : 16
You ticket price is $15.00.
Retrieve your ticket(s) below
Enter your age (enter 'quit' to exit) : QuIt # Caps doesn't matter
Thank You Enjoy the show
It will fix your problem if you do it this way: "if int(age) > 13:"(across all if statements) This way you "quit" functionality will still work! Happy coding!!
I hope this simplification of your code helps:
age = int(input("Enter Age: "))
if age > 13:
print('You ticket price is $15.00.')
print('Retrieve your ticket(s) below')
if age <= 13 and age > 2:
print(f'Your ticket price is $10.00.')
print(f'Retrieve your ticket(s) below')
if age < 3:
print('Your ticket price is free')
print('Retrieve your ticket below')
In the if statements change your numbers from if age < '13': to if age < 13:
(Change on all if statements) Otherwise 13 is read as a string and cannot be used as an int.
I think I have an answer. First, why do you use print(f'')? You can just use print(''). Also, there is no need to type prompt='\nEnter'; you can just type prompt='Enter'!

Convert variable from int to str in a while loop? [duplicate]

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")

Beginner Python - Answering with either a string or a variable in a 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")

Beginner Python - Printing 3 different responses based on age using a while loop

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

Categories

Resources