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

Python if condition and "and"

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

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

+5
source share
4 answers

You can link comparisons this way

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

It works like

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

except that it evaluates foo (a) only once.

+12
source

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

Here you can simply replace

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

with

if foo(a) == 1:

foo(a) != Noneis redundant: if foo(a) == 1guaranteed not to be None.

+7
source

The following statement

if foo(a) == 1:

will deal with both conditions.

+1
source

if foo (a) == 1, then foo (a) will not be None,

so simplify your code:

if foo(a):
    print('asdf')
+1
source

All Articles