简体   繁体   中英

Exception statement not working with Python code

I have following code and I am trying to use exception in this, however, when I enter the string value in age rather than integer it is still throwing Value Error. Any suggestion is appreciated.

name = input("Please provide you name: ")
age = int(input("Please provide your age: "))
year = 2022
try:
    if age == 21:
        print(f"Hi {name}, you are already 21.")
    elif age < 0:
        print("Age cannot be less than 0.")
    elif age < 21:
        gap = year - age
        birth_year = gap + 21
        print(f"Hi {name}, you will be 21 in {birth_year}.")
    elif age > 21:
        gap = year - age
        birth_year = gap + 21
        print(f"Hi {name}, you turned 21 in {birth_year}.")
except ValueError:
    print("Invalid Input.")

This is because this:

 age = int(input("Please provide your age: "))

should be below the try:

try:
   age = int(input("Please provide your age: "))

you are trying to convert string to int and this is why this fails

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM