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

Matt Fuller
Matt Fuller
941 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

1 Answer

Chris Freeman
MOD
Chris Freeman
Treehouse Moderator 57,148 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
941 Points

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