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 trialRachael A
1,044 PointsI can't seem to pass the final Python Basics question
I have no idea what's going on here. Also I don't understand the return not part in this code. I think my code is close can anyone help me please?
import random
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
start = 5
while start != 0:
num = random.randint(1, 99)
if even_odd(num) == 0:
print("{} is even").format(num)
else:
print("{} is odd").format(num)
start -= 1
4 Answers
dojewqveaq
11,393 PointsHey Rachel,
I see that quite a few people are having problem with this task. I think that's mainly because the "return not" is a bit confusing. I'll try to explain as best as I can.
In python, when we say:
return something
This already evaluates to True... So if you use the not, like in the task:
return not something
This evaluates to false, since "not" reverses the result of the code.
With that said, "def even_odd()" returns True if the num is NOT divisible by 2, and False if it is.
Now, looking at your code, you wrote:
if even_odd(num) == 0
That will never be true, since def even_odd() returns a boolean. Here is how I solved the task:
import random
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
start = 5
while start:
num = random.randint(1, 99)
if even_odd(num):
print("{} is even".format(num))
else:
print("{} is odd".format(num))
start -= 1
Post back if you need more help with this. =)
Rachael A
1,044 PointsWhat do you mean by main?
Rachael A
1,044 PointsThanks for the explanation. Your code looks correct but shouldn't start be start -= 1? I'll have to try the code again later cos I keep getting communication errors now.
dojewqveaq
11,393 PointsYes! My mystake there! decrement the start variable by one using -=.
Rachael A
1,044 PointsI finally passed this, thanks for helping! The even_odd function was really confusing but I understand it a bit better now.
Gilbert Craig
2,102 PointsGilbert Craig
2,102 PointsYou appear to be using the argument 'num' also as a variable.
i.e change num to random_num where you use it in the main.