Read section 6.2 in the book and do the examples.
Scaffolding is an extremely common tool. I use it anytime I'm getting into anything tricky. If I can't figure out a bug, I flood my code with print statements in order to figure out where a problem is.
Read sections 6.3 and 6.4 in the book and do the examples.
Let's use both of these tools to write two functions: is_even and is_odd. First, is_even:
def is_even(integer): """Returns whether number is even.""" if integer % 2 == 0: return True else: return False
Tests!
>>> is_even(44) True >>> is_even(43) False >>> is_even(-653) False >>>
Notice that we're returning True if a condition is True and returning False when that condition is False. We can improve the code by replacing the entire conditional with just returning the condition.
def is_even(integer): """Returns whether number is even.""" return integer % 2 == 0
Test it again to make sure it still works.
It's very easy to write is_odd by just changing one character in the body, but let's write it differently to use composition!
def is_odd(integer): """Returns whether number is odd.""" even = is_even(integer) if even: return False else: return True
Looks good! Can we do a similar thing as before to remove the conditional? Unfortunately, we're returning False when the condition is True and vice-versa. I know I can fix it by just putting a not in front of the condition, but let me fix it in two steps to convince you that it works that way. First, change the local variable so that it represents the opposite of evenness and flip the conditional to use the new values.
def is_odd(integer): """Returns whether number is odd.""" odd = not is_even(integer) if odd: return True else: return False
Then we can update the method to just return the condition.
def is_odd(integer): """Returns whether number is odd.""" odd = not is_even(integer) return odd
You can further compress that into one line if you like.