Python: Modules
A Python file with functions and constants is called a module. You can connect it to your program using the import keyword and use ready-made code instead of writing it yourself.
Python comes with a standard library — a set of modules included with the language. One of the most commonly used is math, which provides mathematical functions and constants.
Importing a Module
The import command at the top of a file makes the module's contents available:
import math
print(math.floor(3.7)) # => 3
print(math.ceil(3.2)) # => 4After importing, you access functions through the module name and a dot. math.ceil(3.2) calls the ceil function from the math module.
Functions in the math Module
floor rounds a number down to the nearest integer, ceil rounds it up:
import math
print(math.floor(7.9)) # => 7
print(math.ceil(7.1)) # => 8
print(math.ceil(7.0)) # => 7The difference matters when the number is not whole. floor(7.9) gives 7, not 8, because 7 is the nearest integer below.
Importing Specific Names
When you only need part of a module, you can import specific names:
from math import ceil, floor
print(ceil(3.2)) # => 4
print(floor(3.7)) # => 3This lets you use ceil and floor directly, without the math. prefix. The result is the same as using import math.
Using a Module Inside a Function
An imported module is available throughout the file, including inside function bodies:
import math
def trips_needed(items: int, capacity: int) -> int:
return math.ceil(items / capacity)
print(trips_needed(10, 3)) # => 4The function trips_needed uses math.ceil. The import math line at the top of the file makes this possible.
Instructions
Implement the function amount_per_person(). It takes the restaurant bill total, the number of people, and the tip percentage, and returns the amount each person pays. The result is rounded up — nobody should underpay.
Use the math.ceil() function from the math module for rounding.
# Bill 300, 4 people, 20% tip — total 360, each pays 90
print(amount_per_person(300, 4, 20)) # => 90
# Bill 350, 3 people, 10% tip — total 385, each pays 129
print(amount_per_person(350, 3, 10)) # => 129Hint
- First calculate the total with tip, then divide by the number of people and round up
- Don't forget to import the
mathmodule at the top of the file
If you've reached a deadlock it's time to ask your question in the «Discussions». How ask a question correctly:
- Be sure to attach the test output, without it it's almost impossible to figure out what went wrong, even if you show your code. It's complicated for developers to execute code in their heads, but having a mistake before their eyes most probably will be helpful.
Your exercise will be checked with these tests:
import solution
def test():
assert solution.amount_per_person(300, 4, 0) == 75
assert solution.amount_per_person(300, 4, 20) == 90
assert solution.amount_per_person(350, 3, 10) == 129
assert solution.amount_per_person(100, 3, 0) == 34Teacher's solution will be available in:
20:00
