Search code examples
pythontry-catchexcept

try - except struggle


I am trying to stop this program if the number the person enters is not 4 numbers long, using the try-except structure. I don't really get why it skips the except block if I enter a 2 or 3 digit number for example. All help appreciated.

guess = int(input('Guess a 4 digit number:\n'))
guesslist = [int(x) for x in (str(guess))]
x = 0
y = 0

try:
    print(len(str(guess)))
    len(str(guess)) == 4

except:
    print('please enter a 4 digit number')
    quit()

print('past')

Solution

  • The try/except syntax catches exceptions (aka errors). If there are no errors thrown by the code in a try clause, the except clause is skipped. You don't have any obvious errors in your try clause.

    From the try/except docs:

    First, the try clause (the statement(s) between the try and except keywords) is executed. If no exception occurs, the except clause is skipped and execution of the try statement is finished.

    Use if/then conditional syntax instead:

    if len(str(guess)) == 4:
        print(len(str(guess)))
    else:
        print('please enter a 4 digit number')
        quit()