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 Practice Creating and Using Functions in Python Practice Functions That's Odd

Practice Creating and Using Functions in Python - task two

I really don't get this one. Completely new to coding and struggling to remember it all, can anyone just walk me through

There is only one task. What is task two?

2 Answers

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 68,423 Points

The task asks Create a function that determines if a specific value is odd. Specifically:

  • Create a function. This is done by include the keywork def in front of a variable and including a parameter list in parens, followed by a colon
def function_name(parameters):
  • Name the function is_odd
def is_odd(parameters):
  • have it declare a single parameter. This can be any variable name, let's use value
def is_odd(value):
  • return True if the value is not divisible by 2. The Python way to check if a value is even is to use the modulo operator % with 2. A zero result is even, a one result is odd
is_odd_value = False
if value %2 == 1:
    is_odd_value = True
  • Return result
    return is_odd_value

Time to simplify the code

Instead of checking a Boolean (true/false) statement to set a Boolean value, just use the Boolean value directly

    is_odd_value = value %2 == 1
    return is_odd_value

But since value % 2 returns either a 0 or a 1, and 0 is equivalent to False and 1 is equivalent to True you can use the results of the modulo directly to get an even result.

    # adding not and changing 0 to 1
    is_odd_value = not value %2 == 0
    # or, simply
    is_odd_value = not value %2

Returning the result:

    # Return results
    return is_odd_value
    # or simply
    return not value % 2

Post back if you need more help. Good luck!!

Thank you so much for taking the time to write that explanation out, it really helped me solidify my understanding!

Sammy Ramadan
Sammy Ramadan
558 Points

Perfectly put. Cheers Chris!

whaoww...that helped thanks