Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python if condition and "and"

Tags:

python

 >>> def foo(a):
        print "called the function"
        if(a==1):
            return 1
        else:
            return None
>>> a=1

>>> if(foo(a) != None and foo(a) ==1):
    print "asdf"

called the function
called the function
asdf

Hi. how can i avoid calling the function twice without using an extra variable.

like image 490
boltsfrombluesky Avatar asked Mar 14 '13 11:03

boltsfrombluesky


1 Answers

You can chain the comparisons like this

if None != foo(a) == 1:

This works like

if (None != foo(a)) and (foo(a) == 1):

except that it only evaluates foo(a) once.

like image 93
John La Rooy Avatar answered Nov 06 '22 18:11

John La Rooy