Search⌘ K
AI Features

Introduction to Modules and Libraries

Explore how to use Python modules and libraries to add powerful features to your code. Learn to import and utilize tools from modules such as random, math, and datetime to perform tasks like generating random values, calculating mathematical functions, and working with date and time in your programs.

Python is powerful because of its syntax and amazing libraries—prebuilt collections of code that do awesome things, so you don’t have to start from scratch.

In this lesson, we’ll explore how to use these libraries (also called modules) to supercharge your code.

What’s a module?

A module is like a toolbox. We can import it into our code and start using its functions, classes, constants, and more tools.

Let’s use the following:

import turtle
Accessing the turtle module to draw on the screen

Let’s try a few more built-in modules.

Random module: Make random choices

Let’s flip a coin with random. Run the code below a few times—it changes!

Python
import random
coin = random.choice(["heads", "tails"])
print("You flipped:", coin)

You just used randomness in your code.

Math module: More powerful math

Let’s find the square root of 64 and print the value of pi using the math library:

Python
import math
print(math.sqrt(64)) # Square root
print(math.pi) # Pi constant

You now have the power of square roots and π!

Datetime module: Use time

Let’s print the current date and time:

Python
from datetime import datetime
now = datetime.now()
print("Current time:", now)

Now your program knows the date and time—useful for logs and trackers!