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

Help with Practice Creating and Using Functions in Python

I'm stuck

Let's create a function that determines if a specific value is odd. Let's name the function is_odd and have it declare a single parameter. It should return True if the value is not divisible by 2.

def is_odd(number):
    is_odd = number % 2 == 0
    return is_odd + 1
Ran 1 test in 0.000s
OK
F.
======================================================================
FAIL: test_evens (__main__.TestFunctionDefinitionExecution)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "", line 59, in test_evens
AssertionError: 2 is not false : Uh oh, 2 is even but it is_odd(2) returned True

----------------------------------------------------------------------
Ran 2 tests in 0.000s
FAILED (failures=1)

MOD: I added some formatting to your code and the challenge output so they're easier to read here, and easier for us the help you. You can find how to do this in the Markdown Cheatsheet that's linked right below the text box for question and answer posts. Thanks! :-)

1 Answer

Hi Vlad,

There are a couple of things here. One is that you have your comparison backwards:

# This will be True if the number is even, but you are setting it to is_odd
number % 2 == 0

# To check for an odd number, use:
number % 2 == 1

Also, in your code, is_odd turns out to be either True or False. But then you add 1 to it (not sure why?), which changes it from a boolean to an integer. So your code is returning either 1 or 2, when it should be returning either True or False.

If you want, you can simplify the contents of your function to a single line, by directly returning the results of your comparison. For example, these two are equivalent:

# A corrected version of your original code.
# I might put parentheses around the right side of your first line,
# just to make it clearer what is happening.
def is_odd(number):
    is_odd = (number % 2 == 1)
    return is_odd

# This code returns the same thing:
def is_odd(number):
    return number % 2 == 1

I hope this helps!