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" in Python

Hi, I don't really get how return works in Python, and how to use it. For example, I was stuck on a challenge (the last one I think in Python Basics): They included for me "return not num % 2" when num % 2 was 1. How can you use these return blocks in an "if" block? Do you know what lesson explains the return method?

1 Answer

Steven Parker
Steven Parker
243,318 Points

The return statement in Python is very similar to other languages. It is only used inside a function, and it causes the function execution to end. Any parameter it is given is evaluated and passed back to the caller of the function as the function's value.

So a function that contains "return not num % 2" will give the caller the result of evaluating "not num % 2", which means the function's value will be true when num is even, and false when num is odd.

Does that help?

Ok, so does this work?

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.

if num % 2 == 1:

    return not num % 2

elif num % 2 == 0:

    return num % 2

while start:

num = random.randint(1, 99)

if not num % 2:

    print("{} is even".format(num))

elif num % 2:

    print("{} is odd".format(num))

Thanks. It turned out to be a simple mistake I overlooked.