MSIT

Import a module

import math loads the math module. After that, math.sqrt(9) is the square root of 9, and math.pi is the circle constant.

The name before the dot is the module. The name after the dot is the function or the value inside it.

Why math exists

Square root is easy to describe and easy to get slightly wrong. A loop that guesses the root can stop too early, or fail on zero. The math module already contains a tested sqrt, plus pi, floor, ceil, and other tools. You import that module instead of reinventing one function every time a program needs a root.

math is part of the standard library. It arrives with Python. import loads it. It does not download a new language.

A circle marked with radius, diameter, and other lines
Circle measurements use values from the math module, including math.pi.

This module provides access to common mathematical functions and constants, including those defined by the C standard.

— Python documentation, math

The name before the dot

One import line creates one module name. Everything you need from that file hangs off the dot.

  • math.sqrt is a function. You call it with parentheses.
  • math.pi is a value. You do not call it.
  • math.floor is another function in the same module. One import covers all of them.

math.sqrt(9) prints 3.0, a float. In Python, 3.0 equals 3, so a function that returns math.sqrt(number) is returning the square root even though the printed form has a decimal point.

There is a second spelling, from math import sqrt, which copies sqrt into your file so you can call it without the dot. This lesson uses import math and the dot. That spelling makes it obvious which module the name came from.

This program cannot be stepped through.

What does import math do?

Click the line that loads a module.


Put the lines in an order that prints 3.0.

import math
print(math.sqrt)
print(math.sqrt(9))

A worked example

root should take one number and hand back its square root. The module already has that function. Your function only has to pass the number through.

  1. Import math.
  2. Define root with one parameter, number.
  3. Return math.sqrt(number).

Call root(16). The parameter number is 16. math.sqrt(16) is 4.0. That float is the return value. Call root(0) and the same path returns 0.0, which equals 0. The function does not print. It returns, so a caller can use the result.

math.sqrt of a negative number raises ValueError. Stay with zero and positive numbers here.

Return the call. Do not return the name math.sqrt without parentheses.

Which expression is the square root of 9?

Exercise

Write a function named root that takes a number and returns its square root. Use the math module.

Write a function named root that takes a number and returns its square root. Use the math module.

Output