-2

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')
robbah
  • 43
  • 6
  • 2
    a `try` is not an `if`. The `except` triggers only when an `Error` is thrown inside the `try`; not if a test fails. – Ma0 Aug 14 '18 at 07:20

3 Answers3

0

Try adding an assert to len(str(guess)) == 4 so it is assert len(str(guess)) == 4.

The reason why is that just having len(str(guess)) == 4 is useless - that is run but you haven't told Python to do anything with the result. If you assert, it basically means verify the next code is true, otherwise throw an exception.

RealPawPaw
  • 988
  • 5
  • 9
  • You shouldn't really use assert statements for this kind of thing, as they are for debugging: https://docs.python.org/3/reference/simple_stmts.html#the-assert-statement – jonrsharpe Aug 14 '18 at 07:25
0

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()
andrew_reece
  • 20,390
  • 3
  • 33
  • 58
0

You need to raise an exception in order to trigger the except. Try it like this:

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)))
    if(len(str(guess)) != 4):
        raise Exception("Invalud number")

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

print('past')
ibarrond
  • 6,617
  • 4
  • 26
  • 45