3

I'm learning about Python's boolean logic and how you can shorten things down. Are the two expressions in the title equivalent? If not, what are the differences between them?

1
  • FirebladeDan... both evaluate to the remainder, and both evaluate to either True or False. Inherently, if there's a remainder, it evaluates to True. If there isn't a remainder, it evaluates to False. You can just as well do if 5 % 2 == True or if 4 % 2 == False
    – stevieb
    Aug 5, 2015 at 15:57

3 Answers 3

11

number % 2 is 0 (so False) if number is even

number % 2 == 0 is True is number is even

The first returns an int where the second returns a bool. Python's truthiness lets you handle them the same though.

2
  • #Pro. Learned something today Aug 5, 2015 at 15:53
  • Basically not num % 2 is the same as number % 2 == 0 Aug 5, 2015 at 15:56
2

number % 2

is equal to (shorthand for)

number % 2 != 0

because 1 evaluates to True and 0 to False.

1

Its simple. you can try on your terminal:

Python 2.7.6 (default, Sep  9 2014, 15:04:36) 
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.39)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> if 5%2:
...     print "T"
... 
T
>>> if 5%2 == 0:
...     print "T"
... 
>>> 

1) if condition looks for answer >1.
2) In a) you're looking if answer is >1 in b) you're looking if answer == 0 (if so like in all other language == will return 1)

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.