I am having issue with running this code. When I try to run it, it says it won't work because age is a string. How do I convert the string to an integer? I have also tried to do 18 - int(age) and that won't work either.
age = input ("How old are you? (): ")
if int(age) > 18 :
print("You're old enough to drink")
else:
print("You're not old enough to drink. Wait", + 18 - age, "more years")
age = input("How old are you? (): "))
try:
age = int(age)
if age > 18 :
print("You're old enough to drink.")
else:
print(f"You're not old enough to drink. Wait {18-age} more years.")
except:
print("You did not enter a valid age.")
Note that input("How old are you? (): ") is int(input("How old are you? (): "))
age = int(input("How old are you? (): "))
if int(age) > 18 :
print("You're old enough to drink")
else:
print("You're not old enough to drink. Wait {} more years".format(18-age))
You can add try.. except..
Like this:
age = input("How old are you? (): "))
try:
age = int(age)
if age > 18 :
print("You're old enough to drink.")
else:
print(f"You're not old enough to drink. Wait {18-age} more years.")
except ValueError:
print("Not a valid age. Please enter again")
and by the way, you can use f' strings for string format.
or use .format :
print("You're not old enough to drink. Wait {0} more years.".format(18-age))
while True:
age = input ("How old are you? ")
#Check if the input is a positive integer
if age.isdigit() >0:
break
if int(age) > 18 :
print("You're old enough to drink.")
else:
print("You're not old enough to drink. Wait",18 - int(age), "more years.")
#Remove the + in 18 because you already use comma after'Wait'
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'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')
This question already has answers here:
Python check for integer input
(3 answers)
Closed 5 years ago.
I am trying to do a program that asks the user his name, age, and the number of times he wants to see the answer. The program will output when he will turn 100 and will be repeated a certain number of times.
What is hard for me is to make the program asks a number to the user when he enters a text.
Here is my program:
def input_num(msg):
while True:
try :
num=int(input(msg))
except ValueError :
print("That's not a number")
else:
return num
print("This will never get run")
break
name=input("What is your name? ")
age=int(input("How old are you? "))
copy=int(input("How many times? "))
year=2017-age+100
msg="Hello {}. You will turn 100 years old in {}\n".format(name, year)
for i in range(copy):
print(msg)
When you're prompting your user for the age: age=int(input("How old are you? ")) you're not using your input_num() method.
This should work for you - using the method you wrote.
def input_num(msg):
while True:
try:
num = int(input(msg))
except ValueError:
print("That's not a number")
else:
return num
name = input("What is your name? ")
age = input_num("How old are you? ") # <----
copy = int(input("How many times? "))
year = 2017 - age + 100
msg = "Hello {}. You will turn 100 years old in {}\n".format(name, year)
for i in range(copy):
print(msg)
This will check if the user input is an integer.
age = input("How old are you? ")
try:
age_integer = int(age)
except ValueError:
print "I am afraid {} is not a number".format(age)
Put that into a while loop and you're good to go.
while not age:
age = input("How old are you? ")
try:
age_integer = int(age)
except ValueError:
age = None
print "I am afraid {} is not a number".format(age)
(I took the code from this SO Answer)
Another good solution is from this blog post.
def inputNumber(message):
while True:
try:
userInput = int(input(message))
except ValueError:
print("Not an integer! Try again.")
continue
else:
return userInput
break
print("Hello there")
name=input("What is your name?")
print("Welcome to the some game, " + name + "!")
print("I'm going to ask you some basic questions so that we could work together")
age=input("Your age")
if age >= 14 and age < 41:
print("K")
else:
print("Sorry bruh")
print("Thanks")
keeps showing me "Sorry bruh" at the end when entered 15. Why? What's wrong?
Cast your input to int:
age = int(input("Your age"))
You could add a try-except. Your condition should equally be evaluated on or not and
Either you use Python3 and you need to cast with int(input("Your age")) or you use Python2 and then you need to use raw_input to read the name: name=raw_input("What is your name?")
Ok , so you can try this code in python2.7 and it will work as you desired:
print("Hello there")
name=raw_input("What is your name?")
print("Welcome to the some game, " + name + "!")
print("I'm going to ask you some basic questions so that we could work together")
age=input("Your age")
if age >= 14 and age < 41:
print("K")
else:
print("Sorry bruh")
print("Thanks")
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")