**
Exercises
**
1.
Many programming languages have sign available as a built-in function. Python doesn’t, but we can define our own!
In the cell below, define a function called sign which takes a numerical argument and returns -1 if it’s negative, 1 if it’s positive, and 0 if it’s 0.
# Your code goes here. Define a function called 'sign'
def sign(num):
if num > 0:
num = 1
elif num < 0:
num = -1
else:
num = 0
return num
# Check your answer
q1.check()
Correct
We’ve decided to add “logging” to our to_smash function from the previous exercise.
def to_smash(total_candies):
"""Return the number of leftover candies that must be smashed after distributing
the given number of candies evenly between 3 friends.
>>> to_smash(91)
1
"""
print("Splitting", total_candies, "candies")
return total_candies % 3
to_smash(91)
Splitting 91 candies
1
What happens if we call it with total_candies = 1?
to_smash(1)
Splitting 1 candies
1
That isn’t great grammar!
Modify the definition in the cell below to correct the grammar of our print statement. (If there’s only one candy, we should use the singular “candy” instead of the plural “candies”)
def to_smash(total_candies):
"""Return the number of leftover candies that must be smashed after distributing
the given number of candies evenly between 3 friends.
>>> to_smash(91)
1
"""
print("Splitting", total_candies, "candy" if total_candies == 1 else "candies")
return total_candies % 3
to_smash(91)
to_smash(1)
Splitting 91 candies
Splitting 1 candy
1
- 🌶️
In the main lesson we talked about deciding whether we’re prepared for the weather. I said th