Neil A.
Neil A.

Reputation: 841

Python order of conditions

When I enter this code, the program never throws an error, even if I enter a non-number:

user_input = input("Enter a number.")
if user_input.isdigit() and 0 <= float(user_input) <= 10:
    print("A number between 0 and 10.")
else:
    print("Not a number between 0 and 10.")

But, if I enter this code, the program throws an error if I enter a non-number:

user_input = input("Enter a number.")
if 0 <= float(user_input) <= 10 and user_input.isdigit():
    print("A number between 0 and 10.")
else:
    print("Not a number between 0 and 10.")

Does anyone know why? Does it really make a difference in which order I type conditions?

Upvotes: 0

Views: 382

Answers (2)

joel goldstick
joel goldstick

Reputation: 4493

In the first case, the isdigit() method is false, so the next condition is not checked. In the second case, the float() is attempted and raises and exception:

... float('bob')
Traceback (most recent call last):
  File "<stdin>", line 2, in <module>
ValueError: could not convert string to float: bob
>>> 

Upvotes: 0

DeepSpace
DeepSpace

Reputation: 81594

Of course it matters.

if 0 <= float(user_input) <= 10 and user_input.isdigit():

First tries to evaluate float(user_input). If user_input is a non-number string it would raise a ValueError.


if user_input.isdigit() and 0 <= float(user_input) <= 10:

First tries to evaluate user_input.isdigit(). If it returns False then 0 <= float(user_input) <= 10 isn't evaluated at all.

This behavior is called "short-circuiting". In the predicate A AND B, B will be evaluated only if A is True. Likewise, in the predicate A OR B, B will be evaluated only if A is False.

Upvotes: 2

Related Questions