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

Time:03-08

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.

CodePudding user response:

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

CodePudding user response:

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.

  • Related