Python Libraries
✕1. 📦 Python Libraries
- A library is a collection of ready-made code that we can use in our program. Instead of writing everything from scratch, we can import a library and use its functions, classes, and tools.
Example:
If we want to generate random numbers, we do not need to build a random number generator ourselves. We can use Python's
randomlibrary. If we want to work with dates and time, we can use Python'sdatetimelibrary. If we want to work with data tables, we can usepandas. Libraries help us: ✅ Save time ✅ Write less code ✅ Use tested and reusable tools ✅ Build practical projects faster - Python libraries can be grouped into two main types:
Built-in libraries:
These come with Python. We do not need to install them separately.
Examples:
- os
- random
- math
- datetime
Third-party libraries:
These do not come with Python by default. We need to install them using pip.
Examples:
- requests
- beautifulsoup4
- pandas
- matplotlib
- mailerpy
Example installation:
pip install requestspip install pandaspip install matplotlib - Before using a library, we usually need to import it.
Example:
import randomnum = random.randint(1, 10)print(num)We can also import specific functions or classes. Example:from math import sqrtprint(sqrt(16))Output: 4.0
1.1 What is a Library?
1.2 Built-in and Third-party Libraries
1.3 Importing Libraries
2. 🗂️ os Library
- The
oslibrary is a built-in Python library. It provides functions for interacting with the operating system. Use cases: ✅ Working with files ✅ Working with folders ✅ Checking file paths ✅ Getting file size - Example:
import osfolder_name = "practice_folder"if not os.path.exists(folder_name):os.mkdir(folder_name)file_path = f"{folder_name}/hello.txt"with open(file_path, "w", encoding="utf-8") as file_obj:file_obj.write("Hello from Python!")print(os.listdir(folder_name))print(os.path.getsize(file_path))Output example: ['hello.txt'] 18
2.1 What is os Library?
2.2 os Library Example
2.3 Common os Functions
| Function | Description |
|---|---|
os.listdir() | Returns list of files and folders inside a directory. os.listdir("folder") |
os.mkdir() | Creates a new folder. os.mkdir("new_folder") |
os.makedirs() | Creates nested folders if needed. os.makedirs("main_folder/sub_folder", exist_ok=True) |
os.rename() | Renames a file or folder. os.rename("old_name.txt", "new_name.txt") |
os.remove() | Deletes a file. os.remove("file.txt") |
os.rmdir() | Deletes an empty folder. os.rmdir("empty_folder"). 📌 Only removes empty folders. |
os.path.exists() | Checks whether a file or folder exists. os.path.exists("file.txt") |
os.path.getsize() | Returns file size in bytes. os.path.getsize("file.txt") |
3. 🎲 random Library
- The
randomlibrary is a built-in Python library. It provides functions for random operations. Use cases: - Generating random numbers - Selecting random items - Shuffling list items - Creating games - Creating random samples 📌randomis useful for games and simulations. - Example:
import randomsecret_number = random.randint(1, 10)guess = int(input("Guess a number between 1 and 10: "))if guess == secret_number:print("Congratulations!! You Win")else:print(f"You Lose. Number was {secret_number}")
3.1 What is random Library?
3.2 Random Library Example
3.3 Common random Functions
| Function | Description |
|---|---|
random.random() | Returns a random float between 0.0 and 1.0. random.random() |
random.randint(a, b) | Returns a random integer from a to b, both included. random.randint(1, 10) |
random.choice(sequence) | Returns one random item from a sequence. random.choice(["red", "green", "blue"]) |
random.shuffle(list) | Shuffles a list in place. random.shuffle(numbers) |
random.sample(sequence, k) | Returns k unique random items from a sequence. random.sample(numbers, 3) |
4. 🧮 math Library
- The
mathlibrary is a built-in Python library. It provides mathematical functions and constants. Use cases: - Square root - Rounding - Trigonometry - Factorial - HCF/GCD - LCM - Logarithm
4.1 What is math Library?
4.2 Common math Functions
| Function | Description |
|---|---|
math.floor(x) | Returns the largest integer ≤ x. math.floor(3.7) # ➜ 3 |
math.ceil(x) | Returns the smallest integer ≥ x. math.ceil(3.2) # ➜ 4 |
math.sqrt(x) | Returns square root of x. math.sqrt(16) # ➜ 4.0 |
math.pow(x, y) | Returns x raised to the power y. math.pow(2, 3) # ➜ 8.0. 📌 We can also use ** for power. |
math.sin(x) | Returns sine of x (x in radians). math.sin(math.pi / 2) # ➜ 1.0 |
math.cos(x) | Returns cosine of x. math.cos(0) # ➜ 1.0 |
math.tan(x) | Returns tangent of x. math.tan(math.pi / 4) |
math.radians(x) | Converts degree to radians. math.radians(180) |
math.pi | Returns value of pi. math.pi |
math.log(x, base) | Returns logarithm of x with given base. math.log(100, 10) # ➜ 2.0 |
math.factorial(n) | Returns factorial of n. math.factorial(5) # ➜ 120 |
math.gcd(a, b) | Returns greatest common divisor. math.gcd(12, 18) # ➜ 6 |
math.lcm(a, b) | Returns least common multiple. math.lcm(12, 18) # ➜ 36 |
5. 📧 mailerpy Library
mailerpyis a third-party Python library used for sending emails. It can be used to send: - Plain text email - Email using body template - Email with attachments - Email with cc and bcc Installation:pip install mailerpy- If using Gmail, generate an app password from Google account settings. You need to enable two-factor authentication in order to generate an app password. Click here to generate one.
- Example:
from mailerpy import Mailerpassword = "YOUR_GMAIL_APP_GENERATED_PASSWORD"mailer = Mailer("smtp.gmail.com", 587, "[email protected]", password)to_emails = ["[email protected]"]subject = "Test Email from mailerpy"body = "Hello, this is a test email sent using mailerpy library in Python."attachment_list = ["test.txt", "test2.txt"]mailer.send_mail(to_emails, subject, body, attachments=attachment_list)📌 For learning purpose, we are writing password directly in code. 📌 In real projects, do not write password directly in code.
5.1 What is mailerpy?
5.2 Gmail App Password
5.3 Sending Email using mailerpy
6. 📅 datetime Library
- The
datetimelibrary is a built-in Python library. It provides tools for working with dates and times. Use cases: - Getting today's date - Getting current date and time - Formatting date - Converting string into date - Calculating age - Calculating difference between two dates %Y➜ Year with century (e.g. 2026)%y➜ Year without century (e.g. 26)%m➜ Month number (e.g. 01)%B➜ Full month name (e.g. January)%b➜ Short month name (e.g. Jan)%d➜ Day of month (e.g. 01)%A➜ Full weekday name (e.g. Monday)%a➜ Short weekday name (e.g. Mon)%H➜ Hour in 24-hour format (e.g. 13)%I➜ Hour in 12-hour format (e.g. 01)%M➜ Minute (e.g. 34)%S➜ Second (e.g. 56)%p➜ AM or PM (e.g. PM)%j➜ Day of year (e.g. 001)%U➜ Week number, Sunday as first day (e.g. 01)%W➜ Week number, Monday as first day (e.g. 01)%w➜ Weekday number (e.g. 0 means Sunday)- Example:
from datetime import datetime, datedob_text = input("Enter your date of birth in YYYY-MM-DD format: ")dob = datetime.strptime(dob_text, "%Y-%m-%d").date()today = date.today()age = today.year - dob.yearif (today.month, today.day) < (dob.month, dob.day):age = age - 1print(f"Your age is {age} years")
6.1 What is datetime Library?
6.2 Common Datetime Formats
6.3 datetime Example
6.4 Common datetime Functions
| Function | Description |
|---|---|
datetime.now() | Returns current local date and time. datetime.now() |
date.today() | Returns today's date. date.today() |
strftime() | Converts date/datetime object into formatted string. now.strftime("%Y-%m-%d") |
strptime() | Converts date string into datetime object. datetime.strptime(date_text, "%Y-%m-%d") |
timedelta() | Used to add or subtract time. today + timedelta(days=7) |
d2 - d1 | Subtracting two dates returns days difference. (d2 - d1).days |
7. 🌐 requests Library
requestsis a third-party Python library used to send HTTP requests easily. Use cases: - Getting data from websites - Calling APIs - Downloading web content - Sending data to servers Installation:pip install requests- Example:
import requestsresponse = requests.get("https://jsonplaceholder.typicode.com/posts/1")print(response.status_code)print(response.text)Output example: 200 📌 When working with websites or APIs, check response.status_code before using response data. - Some websites or APIs return JSON data.
Example:
import requestsresponse = requests.get("https://jsonplaceholder.typicode.com/posts/1")data = response.json()print(data)print(data["title"])📌response.json()should be used when the response is JSON. 📌 For normal webpages, useresponse.textinstead. - Example:
import requestsresponse = requests.get("https://jsonplaceholder.typicode.com/posts/1")print(response.status_code)print(response.headers)print(response.text)
7.1 What is requests?
7.2 GET Request Example
7.3 Working with JSON Response
7.4 Response Details
8. 🍲 BeautifulSoup Library
- BeautifulSoup is a third-party Python library used to parse HTML and XML documents. It helps us search and extract data from webpages.
Installation:
pip install beautifulsoup4Common methods: -find()-find_all()-select() - Example:
from bs4 import BeautifulSoupimport requestsresponse = requests.get("https://example.com")soup = BeautifulSoup(response.text, "html.parser")print(soup.title.text)Output example: Example Domain - Example:
from bs4 import BeautifulSouphtml_doc = """<html><body><h1>Python Course</h1><p class="intro">Welcome to Python</p><p class="intro">Learn libraries</p></body></html>"""soup = BeautifulSoup(html_doc, "html.parser")heading = soup.find("h1")paragraphs = soup.find_all("p")print(heading.text)for paragraph in paragraphs:print(paragraph.text)
8.1 What is BeautifulSoup?
8.2 BeautifulSoup Example
8.3 Finding Elements
9. 🐼 pandas Library
pandasis a third-party Python library used for working with data. It is commonly used for: - Reading CSV files - Filtering data - Cleaning data - Analyzing data - Exporting data Installation:pip install pandasImport Code:import pandas as pd- Example:
import pandas as pddf = pd.read_csv("data.csv")print(df.head())print(df.describe()) - Example:
import pandas as pddf = pd.read_csv("data.csv")filter_mask = (df["LTP"] > 150) & (df["LTP"] < 300)filtered_data = df[filter_mask]print(filtered_data.head()) - Example:
import pandas as pddf = pd.read_csv("data.csv")filter_mask = (df["LTP"] > 150) & (df["LTP"] < 300)filtered_data = df[filter_mask]filtered_data.to_csv("filtered_data.csv", index=False)📌index=Falseprevents pandas from adding extra index column in CSV.
9.1 What is pandas?
9.2 Reading CSV using pandas
9.3 Filtering Data
9.4 Saving Data to CSV
10. 📈 matplotlib Library
matplotlibis a third-party Python library used for creating visualizations. It can be used to create: - Line plots - Bar charts - Scatter plots - Histograms - Pie charts Installation:pip install matplotlibCommon import:import matplotlib.pyplot as plt- Example:
import matplotlib.pyplot as pltx = [1, 2, 3, 4, 5]y = [10, 20, 25, 30, 40]plt.plot(x, y)plt.title("Line Plot")plt.xlabel("X-axis")plt.ylabel("Y-axis")plt.show() - Example:
import matplotlib.pyplot as pltx = [100, 200, 300, 400]y = [10, 30, 20, 50]plt.scatter(x, y)plt.title("Scatter Plot")plt.xlabel("LTP")plt.ylabel("Volume")plt.show()
10.1 What is matplotlib?
10.2 Line Plot Example
10.3 Scatter Plot Example
Practice QuestionsNot started
1. random Library
Question 1 of 4
- Create a guessing game. The computer randomly selects a number between 1 and 10. Ask the user to guess the number. If the user guesses correctly, display:
Congratulations!! You Win. Otherwise display:You Lose. Number was {num} - Modify the guessing game. The user should get three attempts to guess the number. For incorrect guesses, display:
Incorrect!! Guess higher numberorIncorrect!! Guess lower numberdepending on the user's guess. If the user cannot guess in three attempts, display:You Lose. Number was {num} - Create a Rock, Paper, Scissors game. The computer randomly chooses one option. Ask the user for input. Display
You Win,You Lose, orDrawdepending on the game logic. Ask the user whether they want to replay. - Create a Hangman game. Ask user for level: Easy, Difficult, Hard. Words for the game should be loaded from a JSON file, grouped by level, with each word having a
wordand short description or hint. Rules: First and last letter should be pre-filled. User gets 5 attempts. If user guesses the word, display:You Win. Otherwise display:You Lose, Word was {word}
1.1 Practice tasks using random library:- Create a guessing game. The computer randomly selects a number between 1 and 10. Ask the user to guess the number. If the user guesses correctly, display:
2. random, mailerpy, and os
Question 2 of 4
- Write a function
shuffle_for_flash_gamethat takesnum_of_playeras input. It should return shuffled cards in this form:[{"p1": ["c1", "c2", "c3"]}, {"p2": ["c4", "c5", "c6"]}]. Use random library. - Marketing team has a CSV file of users eligible for lucky draw with headers Name, Number, Email, Address (create the CSV file yourself). Write a program that reads the CSV file, randomly selects three lucky winners, and sends email to each winner using mailerpy with message:
Congratulations!! {Name}. You won. - Create a folder
all_doc. Inside it, manually create multiple Python files and document files (.py, .doc, .docx, .txt). Write a program that creates folderspython_filesanddoc_files, moves Python files intopython_files, moves document files intodoc_files, and displays the number of files moved to each folder. - Create a program that counts and displays number of exercises completed in each course module. Output format:
[{"Module": "Basics", "Exercise": 10, "Lines of Code": 100}, {"Module": "File Handling", "Exercise": 8, "Lines of Code": 120}]
2.1 Practice tasks combining random, mailerpy, and os libraries:- Write a function
3. math and datetime
Question 3 of 4
- Find HCF and LCM of a list of numbers using math library. Example:
numbers = [12, 18, 24] - Calculate factorial of a number using math library. Example:
num = 5 - Assign
x_degree = [0, 30, 45, 60, 90]. Calculate sin(x), cos(x) for each value. Hint: Convert degree to radians before using sin and cos. - Ask user for their date of birth in YYYY-MM-DD format. Calculate and display: Day of the week they were born on, Current age in years, Number of days until next birthday.
- Create a program that takes two dates as input and calculates difference between them in years.
3.1 Practice tasks using math and datetime libraries:- Find HCF and LCM of a list of numbers using math library. Example:
4. requests, BeautifulSoup, pandas, matplotlib, and mailerpy
Question 4 of 4
- Scrape share data from a website and store it in a CSV file. The name of the CSV file should be the date of data, e.g.
2026-04-01.csv. Email the scraped CSV file to[email protected]with subjectShare Data for {date}and bodyData scraped from {url}. Keep yourself in cc. 📌 Make sure the website allows scraping before scraping data. - Load the scraped CSV data using pandas. Filter companies where LTP is between 500 and 5000. Save filtered data as
filtered_share_data.csv. - Load scraped data and create a scatter plot of LTP and Volume. Use matplotlib.
4.1 Practice tasks combining requests, BeautifulSoup, pandas, matplotlib, and mailerpy:- Scrape share data from a website and store it in a CSV file. The name of the CSV file should be the date of data, e.g.
