Navin
Navin

Reputation: 57

Assertion Error, error when there shouldn't be one

try:
    guess = str(int(input("Please enter your guess: ")))
    assert len(guess) == 4
except ValueError or AssertionError:
    print("Please enter a 4 digit number as your guess not a word or a different digit number. ")

Assertion Error Received when I type a number that is not 4 digits.

Upvotes: 0

Views: 831

Answers (2)

Łukasz Rogalski
Łukasz Rogalski

Reputation: 23203

Let's analyze a code structure. I've added parenthesis to denote how Python interpreter groups statements.

try:
    do_something()
except (ValueError or AssertionError):
    handle_error()

Let's check what happens to definition of exception to catch. Quoting official docs:

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

"If x is true" actually refers to x being true in boolean context (value of x.__nonzero__() in Python 2, x.__bool__() in Python 3). All objects (including classes) are implicitly truthy, unless implemented otherwise.

# No exception is raised in either case
assert ValueError
assert AssertionError
# both values after conversion are True
assert bool(ValueError) is True
assert bool(AssertionError) is True

After taking in consideration boolean context of classes and quoted docs about boolean operations, we may safely asssume that (ValueError or AssertionError) evaluates to ValueError.

To catch multiple exception you need to put them in tuple:

try:
    do_something()
except (ValueError, AssertionError):
    handle_error()

Upvotes: 2

dlmeetei
dlmeetei

Reputation: 10371

except ValueError or AssertionError: should be except (ValueError, AssertionError):

When you do or you are not catching the exception AssertionError

Upvotes: 1

Related Questions