Reputation: 9
How are these two Python statements different:
>>> if a==1 and b==2:
pass
>>> if a==1:
if b==2:
pass
Upvotes: 0
Views: 50
Reputation: 312116
If these two statements are the entire code (e.g., there's no else
to match the if
), these two statements will have the same effect.
Upvotes: 2
Reputation: 178090
There is no practical difference. Both must evaluate a==1
and b==2
for pass
to execute, and both "short-circuit" and do not evaluate b==2
if a==1
is False
.
Here's an example of short-circuiting:
>>> a=1
>>> b=2
>>> if a==1 and b==2:
... print('pass')
...
pass
Here, the first statement is True so the second is evaluated, but c
does not exist:
>>> if a==1 and c==2:
... print('pass')
...
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'c' is not defined
>>> if a==1:
... if c==2:
... print('pass')
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
NameError: name 'c' is not defined
Here, the first statement is false so the invalid variable is not evaluated:
>>> a=2
>>> if a==1 and c==2:
... print('pass')
...
>>>
>>> if a==1:
... if c==2:
... print('pass')
...
>>>
Upvotes: 1