A module is a file of ready-made functions and values. Python ships with a large collection of them — the standard library. import makes a module available; its contents are reached with a dot:
import math
print(math.sqrt(25))
print(math.pi)
Output:
5.0
3.141592653589793
import lines go at the top of the file. After import math, the name math works like a variable holding the module.
More from math: math.floor(4.7) is 4 (round down), math.ceil(4.2) is 5 (round up).
There is nothing special about calling a module's functions — math.sqrt behaves exactly like a function you defined yourself, except someone else wrote and tested it. When a task sounds common — square roots, dates, counting — the standard library usually has it, and using it beats rewriting it.
math.circle_area with one parameter, radius. It returns the area: pi times radius squared. Use math.pi.boxes_needed with two parameters: items and per_box. It returns how many boxes hold all the items — the division rounded up. Use math.ceil.circle_area(1) returns 3.141592653589793. boxes_needed(10, 4) returns 3.
Run your code to see the output, then press Submit.
import math
import unittest
class TestImport(unittest.TestCase):
def test_circle_area_of_radius_1_is_pi(self):
self.assertAlmostEqual(circle_area(1), math.pi)
def test_circle_area_of_radius_2(self):
self.assertAlmostEqual(circle_area(2), 4 * math.pi)
def test_10_items_need_3_boxes_of_4(self):
self.assertEqual(boxes_needed(10, 4), 3)
def test_exact_fit_needs_no_extra_box(self):
self.assertEqual(boxes_needed(8, 4), 2)
import math
def circle_area(radius):
return math.pi * radius ** 2
def boxes_needed(items, per_box):
return math.ceil(items / per_box)
print(circle_area(1))
print(boxes_needed(10, 4))
Sign in to join the discussion.
No comments yet. Be the first to ask a question.
Press Run to execute your code, or Submit to test and complete this problem.