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 Python Basics (2015) Letter Game App Even or Odd Loop

I 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?

even.py
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
Gilbert Craig
Gilbert Craig
2,102 Points

You 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.

4 Answers

Hey 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. =)

What do you mean by main?

Thanks 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.

Yes! My mystake there! decrement the start variable by one using -=.

I finally passed this, thanks for helping! The even_odd function was really confusing but I understand it a bit better now.