0

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):
1
  • 1
    Run them with n = p = 0 and see. Commented Jul 28, 2014 at 20:03

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

2 Comments

Just to make things clear: from a pure boolean logic POV, both expressions are indeed equals. From a Python code POV they are not.
Sure, but this is a question tagged Python on StackOverflow, not a logic question on Math SE.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.