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?
3 Answers
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.
number % 2
is equal to (shorthand for)
number % 2 != 0
because 1 evaluates to True and 0 to False.
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)
if 5 % 2 == True
orif 4 % 2 == False