Order of evaluation in conditionals

K

Karlo Lozovina

Hi all! Here is what's bugging me: let's say I have this code:

if (<condition1>) and (<condition2>) and (<condition3>):
do_something()

Is there a guarantee that Python will evaluate those conditions in order (1,
2, 3)? I know I can write that as a nested if, and avoid the problem
altogether, but now I'm curious about this ;).

Thanks...
 
P

Paul Hankin

Hi all! Here is what's bugging me: let's say I have this code:

if (<condition1>) and (<condition2>) and (<condition3>):
  do_something()

Is there a guarantee that Python will evaluate those conditions in order (1,
2, 3)? I know I can write that as a nested if, and avoid the problem
altogether, but now I'm curious about this ;).

Did you try to find the answer to your question in the python
reference manual? The relevant page is http://docs.python.org/ref/Booleans.html

To quote it:
The expression 'x and y' first evaluates x; if x is false, its value
is returned; otherwise, y is evaluated and the resulting value is
returned.
 
T

Tim Chase

if ( said:
do_something()

Is there a guarantee that Python will evaluate those conditions in order (1,
2, 3)? I know I can write that as a nested if, and avoid the problem
altogether, but now I'm curious about this ;).

Yes, Python does short-circuit evaluation, from left-to-right

http://docs.python.org/tut/node7.html#SECTION007700000000000000000

That means that if <condition1> returns false, condition[2|3]
will not be evaluated (and similarly, if condition2 returns
false, condition3 won't be evaluated).

-tkc
 
K

Karlo Lozovina

Paul said:
Did you try to find the answer to your question in the python
reference manual? The relevant page is
http://docs.python.org/ref/Booleans.html

Of course I first Googled (even Google Groups-ed) it, but I didn't notice
that in the results.
To quote it:
The expression 'x and y' first evaluates x; if x is false, its value
is returned; otherwise, y is evaluated and the resulting value is
returned.

Thanks (to both of you :>), that's it.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,001
Messages
2,570,249
Members
46,846
Latest member
BettinaOsw

Latest Threads

Top