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 trialSmith Thapa
7,023 PointsHow does this function even_odd(num) works?
return not num%2 ...what do you mean ?
import random
start=5
def even_odd(num):
# If % 2 is 0, the number is even.
# Since 0 is falsey, we have to invert it with not.
return not num % 2
while start==True :
number= random.randint(1,99)
if
3 Answers
jcorum
71,830 PointsSorry, yes, I misunderstood.
return not num % 2
The remainder operator, %, returns the remainder of dividing the value of num by 2.
For example, if num were 23, then 23 % 2 is 1, which is truthy..
If num were 24, then num % 2 will be 0, which is falsey.
Because the function needs to return truthy when num is even, and falsey when num is odd, it adds not to the expression, to reverse what is returned: falsey when num is odd, truthy when num is even.
It would have been better coding, more self-documenting, if the function's name were is_even() rather than even_odd()!
Hope this helps!
Cindy Lea
Courses Plus Student 6,497 PointsWell first the % function isthe remainder function. If there is a remainder it is true, otherwise its false. So by saying not in front it means return the opposite of what the equation result is.
jcorum
71,830 PointsYou started off correctly. Just need to add the if...else... and use the function (which is ambiguously named odd_even() - but it returns True if the parameter is even):
while start:
num = random.randint(1, 99)
if even_odd(num):
print("{} is even".format(num))
else:
print("{} is odd".format(num))
start -= 1
Smith Thapa
7,023 PointsSir but i was not asking for the solution , I just want to know how the return statement in the function works...
Smith Thapa
7,023 PointsSmith Thapa
7,023 PointsIt definitely helps ! Thank you.