Reputation: 23
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")
Upvotes: 0
Views: 97
Reputation: 1
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'
Upvotes: 0
Reputation: 2277
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))
Upvotes: 0
Reputation: 3973
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.")
Upvotes: 1
Reputation: 113
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))
Upvotes: 0