Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Python

return not num % 2

Hi, I don't quite understand what this does, could anyone give me a further explanation in a simple way please

2 Answers

Hi youssef moustahib,

It's just going to return a boolean value. As I understand it, in python 0 is false, anything other number is true. the not switches the boolean value to it's opposite value (true becomes false, false becomes true).
Some examples to help it make more sense:

4%2 equals 0 which as a boolean expression equates to false
... so not 4%2 (or not false) would return true

5%3 equals 2 which as a boolean expression equates to true
... so not 5%3 (or not true) would return false

In short ANY expression that equals 0 in this context will return true, as it is not false

I hope that clears it up for you. Happy coding, :dizzy:
Dave.

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,468 Points

There are three things going on in the statement:

return not num % 2

The parsing starts from left to right:

  • return something
  • not something
  • something % something

Once parsed, there are resolved in the reverse order:

  • num % 2 says find the result of num modulo 2. This is remainder after dividing num by 2. If num is even, the result will be zero. If num is odd, the result will be 1.
  • the not says invert the logical value of an object. This takes the modulo result and reverses its "truthiness". A 1 (from an odd num) is truthy, so not 1 becomes False. A 0 (from an even num) is not truthy, so not 0 becomes True.
  • the return simply returns the not result.

Therefore:

  • if num is even, True is returned
  • if num is odd, False is returned

Post back if you need more help. Good luck!!!