Welcome to the Treehouse Community

The Treehouse Community is a meeting place for developers, designers, and programmers of all backgrounds and skill levels to get support. Collaborate here on code errors or bugs that you need feedback on, or asking for an extra set of eyes on your latest project. Join thousands of Treehouse students and alumni in the community today. (Note: Only Treehouse students can comment or ask questions, but non-students are welcome to browse our conversations.)

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and a supportive community. Start your free trial today.

Python Practice Creating and Using Functions in Python Practice Functions That's Odd

Matt Fuller
Matt Fuller
8,725 Points

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 67,638 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!!

Matt Fuller
Matt Fuller
8,725 Points

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