Import

import

Import

Video Transcript

In this section, we're going to use import to access other libraries in Python. These libraries contain more useful functions and tools for us to use in our own programs.
In order to use a library, we first have to import it like this:
import math
Now that we have the math library available, we can use the dot operator to access its useful functions inside. Let's try using the sqrt() function in the math library, which finds the square root of a number:
import math

number = 36
square_root = math.sqrt(number)
print(square_root)
# 6
Again, to use a function inside a library, we first write the library's name, followed by a dot, followed by the function we want to access.
If we tried to use this same code without first importing the library, Python would give us an error saying that it doesn't know what we're talking about:
number = 36
square_root = math.sqrt(number)
print(square_root)

# Traceback (most recent call last):
#   File "<stdin>", line 1, in <module>
# NameError: name 'math' is not defined
Here's another example using the random library to generate a random number between 1 and 10:
import random

number = random.randint(1, 10)
print(number)
# random number between 1 and 10
The random.randint() function takes two numbers as arguments. The first is the minimum value, and the second is the maximum value. Then it chooses a random integer between those two values.
This is just a small taste of the enormous number of Python libraries in the world. Using them can help you save time and simplify your code, so check them out!
Last section Next section