[lnkForumImage]
TotalShareware - Download Free Software

Confronta i prezzi di migliaia di prodotti.
Asp Forum
 Home | Login | Register | Search 


 

Forums >

comp.lang.python

Order of evaluation in conditionals

Karlo Lozovina

2/25/2008 9:18:00 PM

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

--
Karlo Lozovina -- Mosor
3 Answers

Paul Hankin

2/25/2008 9:25:00 PM

0

On Feb 25, 9:18 pm, Karlo Lozovina <_kar...@mosor.net> 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
> 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/Boo...

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

2/25/2008 9:31:00 PM

0

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

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

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

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

2/25/2008 9:41:00 PM

0

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

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