This notebook is an exercise in the Python course. You can reference the tutorial at this link.


Try It Yourself

Functions are powerful. Try writing some yourself.

As before, don't forget to run the setup code below before jumping into question 1.

Exercises

1.

Complete the body of the following function according to its docstring.

HINT: Python has a built-in function round.

2.

The help for round says that ndigits (the second argument) may be negative. What do you think will happen when it is? Try some examples in the following cell?

Can you think of a case where this would be useful?

3.

In a previous programming problem, the candy-sharing friends Alice, Bob and Carol tried to split candies evenly. For the sake of their friendship, any candies left over would be smashed. For example, if they collectively bring home 91 candies, they'll take 30 each and smash 1.

Below is a simple function that will calculate the number of candies to smash for any number of total candies.

Modify it so that it optionally takes a second argument representing the number of friends the candies are being split between. If no second argument is provided, it should assume 3 friends, as before.

Update the docstring to reflect this new behaviour.

4. (Optional)

It may not be fun, but reading and understanding error messages will be an important part of your Python career.

Each code cell below contains some commented-out buggy code. For each cell...

  1. Read the code and predict what you think will happen when it's run.
  2. Then uncomment the code and run it to see what happens. (Tip: In the kernel editor, you can highlight several lines and press ctrl+/ to toggle commenting.)
  3. Fix the code (so that it accomplishes its intended purpose without throwing an exception)

Keep Going

Nice job with the code. Next up, you'll learn about conditionals, which you'll need to write interesting programs. Keep going here


Have questions or comments? Visit the Learn Discussion forum to chat with other Learners.