KevsRobots Learning Platform
35% Percent Complete
By Kevin McAleer, 2 Minutes

Python is known for its rich set of libraries and modules which simplifies the coding experience. In this lesson, we will understand what Python libraries and modules are, how to import them, and get a brief look at a few popular libraries.
libraries and modules are.math, random, and datetime.In Python, a module is a file containing Python code. A library is a collection of modules. They define functions, classes, and variables that you can reuse in your programs.
You can use the import keyword to import a module or a library. Once imported, you can use the dot notation to access the functions, classes, and variables defined in that module.
# Importing the math module
import math
# Using a function from the math module
print(math.sqrt(16)) # Prints '4.0'
math ModuleThe math module provides mathematical functions and constants.
import math
# Constants
print(math.pi) # Prints '3.141592653589793'
# Trigonometric functions
print(math.sin(math.pi/2)) # Prints '1.0'
# Logarithmic functions
print(math.log(100, 10)) # Prints '2.0'
random ModuleThe random module provides functions for generating random numbers.
import random
# Generate a random float between 0 and 1
print(random.random())
# Generate a random integer between 1 and 10
print(random.randint(1, 10))
# Randomly choose an item from a list
print(random.choice(['apple', 'banana', 'cherry']))
datetime ModuleThe datetime module provides classes for manipulating dates and times.
import datetime
# Get the current date and time
now = datetime.datetime.now()
print(now)
# Create a specific date
independence_day = datetime.datetime(1776, 7, 4)
print(independence_day)
# Calculate the difference between two dates
delta = now - independence_day
print(delta.days)
In this lesson, you’ve learned about Python libraries and modules. You’ve learned how to import them and explored a few popular libraries: math, random, and datetime. Libraries and modules are powerful tools that allow you to leverage existing code and build complex applications more easily.
You can use the arrows ← → on your keyboard to navigate between lessons.
Comments