PythonLesson 15 of 16

Modules in Python: import and math

A module is a file of ready-made functions you don't have to write yourself. Python ships with hundreds of them, and math is a good one to start with.

Key points

  • import math loads the module; call its functions with a dot: math.sqrt()
  • from math import floor takes one function so you can call it without the dot
  • math.ceil() rounds up, math.floor() rounds down
  • math.pi is π: 3.141592653589793
  • Your own file helpers.py is a module too: import helpers

Example

import mathfrom math import floor print(math.sqrt(3 ** 2 + 4 ** 2))print(round(math.pi, 4))print(math.ceil(7.1), floor(7.9))

Pythagoras says a right triangle with sides 3 and 4 has a hypotenuse of 5.0. ceil and floor round in opposite directions.

Task

How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.

23 guests are coming and cups come in packs of 4. Work out how many packs to buy (packs) and the area of a 30 cm pizza rounded to one decimal (area).

Output

What your program prints appears here.