Having user input take string and int? (Python) - python

prompt = "Enter your age for ticket price"
prompt += "\nEnter quit to exit: "
active = True
while active:
age = input(prompt)
age = int(age)
if age == 'quit':
active = False
elif age < 3:
print("Your ticket is $5")
elif age >= 3 and age < 12:
print("Your ticket is $10")
elif age >= 12:
print("Your ticket is $15")
This is some fairly simple code but I am having one issue. The problem is, for the code to run age has to be converted into an int. However, the program is also supposed to exit when you type in "quit". You can always have another prompt along the lines of "Would you like to add more people?". However, is there a way to make it run without having to prompt another question?

I would suggest getting rid of the active flag, and just breaking when "quit" is entered, like so, then you can safely convert to int, because the code will not reach that point if "quit" was entered:
while True:
age = input(prompt)
if age == "quit":
break
age = int(age)
if age < 3:
print("Your ticket is $5")
elif age < 12:
print("Your ticket is $10")
else:
print("Your ticket is $15")
Note that the age >= 3 and age >= 12 checks are unnecessary, because you have already guaranteed them with the earlier checks.

If you want to add another prompt, you can ask the first prompt before the loop and the other one at the end of it. And if you want to add the prices, you need a variable for it. If you dont want to prompt another question but want more user input, leave the prompt empty.
prompt = "Enter your age for ticket price"
prompt += "\nEnter 'quit' to exit: "
price = 0
user_input = input(prompt)
while True:
if user_input == 'quit':
break
age = int(user_input)
if age < 3:
price += 5
elif age < 12:
price += 10
else:
price += 15
print(f"Your ticket is ${price}")
user_input = input("You can add an age to add another ticket, or enter 'quit' to exit. ")

Related

How to let the user to input string as well as integers in my program?

I have a question. how can I let the user to enter 'quit' (A string) in my program as well as integers? Thank you
message = "Please enter your age.\nEnter quit to exit the program.\n"
age = ""
while age != 'quit':
age = input(messages)
if age == 'quit':
break
age = int(age)
elif age < 3:
print("The ticket you purchased is free.")
elif age >= 3 and age < 13:
print("The ticket you purchased cost $10.")
elif age >= 13:
print("The ticket you purchased cost $15.")
Your code is close to working, but there are two issues:
message = "Please enter your age.\nEnter quit to exit the program.\n"
age = ""
while age != 'quit':
age = input(message) # variable is called message
if age == 'quit':
break
age = int(age)
if age < 3: # start a new if/elif/else block
print("The ticket you purchased is free.")
elif age >= 3 and age < 13:
print("The ticket you purchased cost $10.")
elif age >= 13:
print("The ticket you purchased cost $15.")
I'd also simplify the if/elif/else block to
if age < 3:
print("The ticket you purchased is free.")
elif age < 13: # no need for >= 3 check since that is done above
print("The ticket you purchased cost $10.")
else: # no need for final check since all special cases done above
print("The ticket you purchased cost $15.")

While loop with user input that takes in int() and str() [duplicate]

This question already has answers here:
Asking the user for input until they give a valid response
(22 answers)
Closed 2 years ago.
Very new to programming! I am working through the book Python Crash Course.
Trying to create a simple program to determine ticket pricing. Taking in user input as age but ending the program when user inputs 'done'
Looks like this:
guest_age = ("Please enter your age. ")
while True:
age = input(guest_age)
age = int(age)
if age == 'done':
break
elif age < 3:
print("Your ticket is free!")
elif age <= 12:
print("Your ticket is $10!")
else:
print("Your ticket is $15!")
I am stumped on how to incorporate the done input without getting the
ValueError invalid literal for int() with base 10: 'done'
You need to first check if the input is 'done' before casting. So,
guest_age = ("Please enter your age. ")
while True:
age = input(guest_age)
if age == 'done':
break
age = int(age)
...

How to stop code running when if statement is not fulfilled

I am doing a school project and what i want to add is a line of code that would stop the code from running if age < 15 or if age > 100
I tried break but it would continue to the next line.
while True:
try:
age = int(input("How old are you? "))
except ValueError:
print("Please enter a valid age!")
continue
if age < 15:
print("sorry you are too young to enter the store!")
break
if age > 100:
print("Please come back in the next life")
break
else:
break
print("")
print("Welcome to Jim's Computer Store", name)
print("") while True:
try:
cash = int(input("How much cash do you currently have? $"))
except ValueError:
print("Please enter a valid value! ")
continue
else:
break
I would advise you to proceed step by step. The code in the question is too long for the purpose. When the first step behaves like you want, you can do another step.
Is is this working like you want ?
name = "John"
while True:
try:
age = int(input("How old are you? "))
except ValueError:
print("Please enter a valid age!")
continue
break
# Here, we can assume that 'age' is an integer
if age < 15:
print("sorry you are too young to enter the store!")
exit()
if age > 100:
print("Please come back in the next life")
exit()
print("")
print("Welcome to Jim's Computer Store", name)
# When the code above will be validated, the next step will be easy
The while loop is to assure that age is an integer when he breaks the loop (if age is not an integer, the program will execute the continue instruction and go back to the start of the loop).
Just adding a exit() after the if condition will do the job.
An example would be:
x = 5
if x < 2:
print "It works"
else:
exit()
Or without the else statement:
x = 5
if x < 2:
print "It works"
exit()

Why the While loop keep running in the following Python code?

I am new to Python, and could not figure out why the While loop is kept running in the following code?
prompt = "Please enter the customer's age: "
age = input(prompt)
while age != 'quit':
age = int(age)
if age <= 3:
print("Welcome little buddy, no charges for you!")
elif age > 3 and age < 12:
print("The ticket price is $10")
elif age >= 12:
print("The ticket price is 15")
elif age == 'quit':
print("rerun the code")
i think you expect this from your code..i did some changes.your while loop didn't stop because it didn't have a reason to stop.it is testing same value again and again against condition
def agetest():
age = input("Please enter the customer's age: ")
age = int(age)
if 0<age <= 3:
print("Welcome little buddy, no charges for you!")
agetest()
elif age > 3 and age < 12:
print("The ticket price is $10")
agetest()
elif age >= 12:
print("The ticket price is 15")
agetest()
elif age == -1:
print("thnks")
agetest()
here is the answer with while loop
age=0
while(age!= -1):
print("Please enter the customer's age: ")
age = int(input())
if 0<age <= 3:
print("Welcome little buddy, no charges for you!")
elif age > 3 and age < 12:
print("The ticket price is $10")
elif age >= 12:
print("The ticket price is 15")
elif age == -1:
print("thanks")
I have taken your code and did some modifications.
problems were :
you were getting input out the loop so it was not interactive.
there was no statement to modify age to break the loop.
you can not cast the input as integer if you are expecting a string input.
while True:
prompt = "Please enter the customer's age: "
age = input(prompt)
if age == 'quit':
print("rerun the code")
break
elif age <= 3:
print("Welcome little buddy, no charges for you!")
elif age > 3 and age < 12:
print("The ticket price is $10")
elif age >= 12:
print("The ticket price is 15")

Getting error message when trying to break out of a while loop in Python

I'm trying to write code that includes the following:
1) Uses a conditional test in the while statement to stop the loop.
2) Uses an active variable to control how long the loop runs.
3) Use a break statement to exit the loop when the user enters a 'quit' value.
Here is my code:
prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
I believe I've answered part 1 and 2 correctly but whenever I enter 'quit' or any other word to test for part 3, I get an error message that states: "ValueError: invalid literal for int() with base 10: 'quit'"
Does anyone have any suggestions of what I may be doing wrong in my code? Thank you for your time.
You are converting the user's input to a number before checking if that input is actually a number. Go from this:
age = input(prompt)
age = int(age)
if age == 'quit':
break
elif age < 3:
print("Your ticket is free.")
To this:
age = input(prompt)
if age == 'quit':
break
age = int(age)
if age < 3:
print("Your ticket is free.")
This will check for a request to exit before assuming that the user entered a number.
You convert age to an integer with int() so it will never equal 'quit'. Do the quit check first, then convert to integer:
age = input(prompt)
if age == 'quit':
break;
age = int(age)
...
This now checks if it's equal to a string literal first, so that in the case it is, it breaks correctly. If not, then continue on as usual.
You are casting the string "quit" to integer, and python tells you it's wrong.
This will work :
prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = input(prompt)
if age == 'quit':
break
age = int(age)
if age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
Just for the sake of showing something different, you can actually make use of a try/except here for catching a ValueError and in your exception block, you can check for quit and break accordingly. Furthermore, you can slightly simplify your input prompt to save a couple of lines.
You can also force the casing of quit to lowercase so that you allow it to be written in any casing and just force it to a single case and check for quit (if someone happens to write QuIt or QUIT it will still work).
while True:
age = input("What is your age?\nEnter 'quit' to exit: ")
try:
age = int(age)
if age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
else:
print("Please enter a valid age.")
except ValueError:
if age.lower() == 'quit':
break
As proposed in a comment above you should use raw_input() instead of input in order to handle the user input as a string so that you can check for the 'quit' string. If the user input is not equal to 'quit' then you can try to manage the input string as integer numbers. In case the user passes an invalid string (e.g. something like 'hgkjhfdjghd') you can handle it as an exception.
Find below a piece of code that demonstrates what I described above:
prompt = "What is your age?"
prompt += "\nEnter 'quit' to exit: "
while True:
age = raw_input(prompt)
if age == 'quit':
break
try:
age = int(age)
if age < 3:
print("Your ticket is free.")
elif 3 <= age <=12:
print("Your ticket is $10.")
elif 12 < age:
print("Your ticket is $15.")
except Exception as e:
print 'ERROR:', e
print("Please enter a valid age.")

Categories