-2

Python 3.8.1 Please see the code below:

while True:
    try:
        age = input('What is your age... (x/X to Exit)')

    except ValueError:
        print("Enter valid age only....")

    if age == 'x' or age == 'X':
        break

    if int(age) >= 18:
        print('You are an adult.')
    elif int(age) <= 0:
        print('Age must not be negative or zero')
    else:
        print('Your are under age.')

Except block never executes. If I input sting, code crashes. The output is below:

What is your age... (x/X to Exit)ten

Traceback (most recent call last):

File "test.py", line 11, in

  if int(age) >= 18:

ValueError: invalid literal for int() with base 10: 'ten'

If I change code like below, everything works fine. Code never crashes. I want to know what is the problem in the previous code. Why except block was not executing. I am a student and want to learn Python.

while True:
    try:
        age = input('What is your age... (x/X to Exit)')

        if age == 'x' or age == 'X':
            break

        if int(age) >= 18:
            print('You are an adult.')
        elif int(age) <= 0:
            print('Age must not be negative or zero')
        else:
            print('Your are under age.')

    except ValueError:
        print("Enter valid age only....")
  • Because exception occurs only when you are trying to convert a non-numeric string into integer. The conversion is done out of the try block thus except block won't ever get executed because of that if. – Kulfy Feb 14 at 10:06
  • Seems trivial to me: you tell the code age is an int outside the try/catch in the 1st example. " age = input('What is your age... (x/X to Exit)')" does not make age an int so it will never trigger. Mind that we are not a coding service and this will get closed – Rinzwind Feb 14 at 10:06

Browse other questions tagged or ask your own question.