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
Youssef Moustahib
7,779 Pointsreturn 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
Dave Harker
Courses Plus Student 15,510 PointsIt'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,
Dave.
Chris Freeman
Treehouse Moderator 68,468 PointsThere are three things going on in the statement:
return not num % 2
The parsing starts from left to right:
-
returnsomething -
notsomething - something % something
Once parsed, there are resolved in the reverse order:
-
num % 2says find the result ofnummodulo 2. This is remainder after dividingnumby 2. Ifnumis even, the result will be zero. Ifnumis odd, the result will be 1. - the
notsays invert the logical value of an object. This takes the modulo result and reverses its "truthiness". A 1 (from an oddnum) is truthy, sonot 1becomesFalse. A 0 (from an evennum) is not truthy, sonot 0becomesTrue.
- the
returnsimply returns thenotresult.
Therefore:
- if
numis even,Trueis returned - if
numis odd,Falseis returned
Post back if you need more help. Good luck!!!