2. From import

from module import name loads a module and binds only the names you list, without the module prefix:

  • from math import sqrt binds sqrt directly. After it, the name math is not defined.
  • Import several names with commas: from math import floor, ceil.
  • Rename a name with as: from math import factorial as fact; then you call fact(5).
  • from math import * imports every public name. It hides where names come from, so avoid it.

Both styles can be combined: from math import pi plus import math is valid if you also need the math. prefix for other names.

Coming from JavaScript? from math import sqrt is close to const { sqrt } = Math; import math keeps the whole Math-like object.

#01

Import one name

Use from math import sqrt, then print sqrt(49).

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#02

Import several names

Import floor and ceil from math with a from math import ... statement. Print floor(9.9) and then ceil(9.1), each on its own line.

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#03

Rename with as

Import factorial from math under the name fact using as. Print fact(5).

Print exactly:

Create a free account to save your progress and unlock chapter 2.

#04

Import a constant

Import pi from math and print the area of a circle with radius 3. The area is pi * 3 ** 2.

Print exactly:

Create a free account to save your progress and unlock chapter 2.