WycG
WycG

Reputation: 141

difference in behavior within if statements for python

i had two statements and my friend is claiming to me they are not the same. i believe they are. I was wondering if they are and if they aren't is there an example where the behavior is different.

if (n != p and c/n > 5.15):

if (c/n > 5.15 and n !=p):

Upvotes: 0

Views: 56

Answers (1)

BrenBarn
BrenBarn

Reputation: 251378

They could be different due to the short-circuiting behavior of and. If the first operand of and is false, the second is not evaluated. So if c/n > 5.15 raises an exception (for instance if n is zero), the first if may work (that is, not raise any error) while the second causes an error. Here is an example:

c = 0
n = 0
p = 0

# No error, no output because the condition was not true
>>> if (n != p and c/n > 5.15):
...     print "Okay!"

# Raises an error
>>> if (c/n > 5.15 and n !=p):
...     print "Okay!"
Traceback (most recent call last):
  File "<pyshell#23>", line 1, in <module>
    if (c/n > 5.15 and n !=p):
ZeroDivisionError: division by zero

Upvotes: 6

Related Questions