CodeBlanks Logo Icon CodeBlanks

import

Learn to load modules with import.

Load a module with import

The import keyword loads a module and makes its name available. Items inside the module are accessed with a dot:

import math
print(math.pi)        # 3.14159...
print(math.sqrt(16))  # 4.0

Here the math module is loaded; math.pi and math.sqrt are called with a dot. The module name acts like a namespace.

This is the fundamental way to organise reusable code.

What is a module

A module is a Python file (.py) containing functions and variables. When you import it, all items in that file become available:

# tools.py file
def merhaba():
    print("selam")

# another file
import tools
tools.merhaba()  # selam

Modules that Python itself provides (math, random, os) are called the standard library and require no installation.

Modules are the way to break large programs into parts.

Practice Square root with math.sqrt

Write import math. Then write print(math.sqrt(16)).

Starter code

main.py
# load the math module
# print the square root of 16

Sample solution

main.py
import math
print(math.sqrt(16))

Expected output

4.0

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 After import math, how is sqrt called?

  • math(sqrt(16))
  • sqrt(16)
  • import.sqrt(16)
  • math.sqrt(16) Correct answer

Explanation: import math loads the math namespace; sqrt is called as math.sqrt.

2 Complete the import keyword

Question
____ math
print(math.pi)
Answer
import math
print(math.pi)

Explanation: import math loads the math module.

3 Match import concepts

Term Meaning
import math Loads the module
math.pi Constant
math.sqrt Function
. (dot) Namespace access

All lessons in Beginner