Functions are powerful. Try writing some yourself.
As before, don't forget to run the setup code below before jumping into question 1.
# SETUP. You don't need to worry for now about what this code does or how it works.
from learntools.core import binder; binder.bind(globals())
from learntools.python.ex2 import *
print('Setup complete.')
Complete the body of the following function according to its docstring.
HINT: Python has a built-in function round
.
def round_to_two_places(num):
"""Return the given number rounded to two decimal places.
>>> round_to_two_places(3.14159)
3.14
"""
# Replace this body with your own code.
# ("pass" is a keyword that does literally nothing. We used it as a placeholder
# because after we begin a code block, Python requires at least one line of code)
return ((num * 100)//1)/100
# Check your answer
q1.check()
12.4535//1
# Uncomment the following for a hint
#q1.hint()
# Or uncomment the following to peek at the solution
#q1.solution()
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?
help(round)
round(3.12412,2)
round(12399.12412,-2)
# Check your answer (Run this code cell to receive credit!)
q2.solution()
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.
def to_smash(total_candies, friends=3):
"""Return the number of leftover candies that must be smashed after distributing
the given number of candies evenly between 3 friends.
The number of friends to divide the candies it's optional. If is not set candies
will be splited into 3 friends
>>> to_smash(91)
1
>>> to_smash(91, friends=5)
1
"""
return total_candies % friends
# Check your answer
q3.check()
#q3.hint()
#q3.solution()
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...
ctrl
+/
to toggle commenting.)ruound_to_two_places(9.9999)
x = -10
y = 5
# Which of the two variables above has the smallest absolute value?
smallest_abs = min(abs(x), abs(y))
smallest_abs
help(abs)
def f(x):
y = abs(x)
return y
print(f(5))
Have questions or comments? Visit the Learn Discussion forum to chat with other Learners.