How do I make a condition where if a user doesn't input an integer, it comes up with an error message?

Question:

I’m trying to code in a condition where if a user doesn’t input an integer, it comes up with an error message. I’m using if statements to generate this. How would I do this??

Age=int(input("What is your age in years?"))

if Age>20 and Age<150:
    print("You are an adult")
elif Age>20 and Age>=150:
    print("Not a valid age")
elif Age<20:
    print("still a teenager")
    

If someone inputted £ as their age, is it possible for the message to print as "Invalid number. Please try again." ?

I’ve tried to recode it and it didn’t work.

Answers:

Yes, you can use a try and except block to check if the user’s input is a valid integer. If it is not, the except block will be executed and the error message will be printed. Here’s an example:

Age=input("What is your age in years?")

try:
    Age = int(Age)

    if Age>20 and Age<150:
        print("You are an adult")
    elif Age>20 and Age>=150:
        print("Not a valid age")
    elif Age<20:
        print("still a teenager")

except ValueError:
    print("Invalid number. Please try again.")

In the code above, the try block contains the code that may throw a ValueError exception if the int() function is unable to convert the user’s input to an integer. If this exception is thrown, the except block will be executed and the error message will be printed.

You can also use a while loop to keep prompting the user for input until they provide a valid integer. Here’s an example:

while True:
     Age = input("What is your age in years?")
 
     try:
         Age = int(Age)
 
         if Age>20 and Age<150:
             print("You are an adult")
         elif Age>20 and Age>=150:
             print("Not a valid age")
         elif Age<20:
             print("still a teenager")
 
         break
 
     except ValueError:
         print("Invalid number. Please try again.")

In this example, the while loop will keep prompting the user for input until a valid integer is provided. Once a valid integer is provided, the code will determine which message to print and then exit the loop using the break statement.

Answered By: A.S