Velocity Reviews > Order of evaluation in conditionals

# Order of evaluation in conditionals

Karlo Lozovina
Guest
Posts: n/a

 02-25-2008
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

Thanks...

--
Karlo Lozovina -- Mosor

Paul Hankin
Guest
Posts: n/a

 02-25-2008
On Feb 25, 9:18*pm, Karlo Lozovina <(E-Mail Removed)> wrote:
> 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

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.

--
Paul Hankin

Tim Chase
Guest
Posts: n/a

 02-25-2008
> 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

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

http://docs.python.org/tut/node7.htm...00000000000000

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

Karlo Lozovina
Guest
Posts: n/a

 02-25-2008
Paul Hankin wrote:

> 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.

--
Karlo Lozovina -- Mosor