Python Libraries

1. 📦 Python Libraries

    1.1 What is a Library?
    1. 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 random library. If we want to work with dates and time, we can use Python's datetime library. If we want to work with data tables, we can use pandas. Libraries help us: ✅ Save time ✅ Write less code ✅ Use tested and reusable tools ✅ Build practical projects faster
    1.2 Built-in and Third-party Libraries
    1. 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 requests pip install pandas pip install matplotlib
    1.3 Importing Libraries
    1. 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

2. 🗂️ os Library

    2.1 What is os Library?
    1. The os library 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
    2.2 os Library Example
    1. 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.3 Common os Functions
FunctionDescription
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

    3.1 What is random Library?
    1. The random library 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 📌 random is useful for games and simulations.
    3.2 Random Library Example
    1. 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.3 Common random Functions
FunctionDescription
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

    4.1 What is math Library?
    1. The math library is a built-in Python library. It provides mathematical functions and constants. Use cases: - Square root - Rounding - Trigonometry - Factorial - HCF/GCD - LCM - Logarithm
4.2 Common math Functions
FunctionDescription
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.piReturns 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

    5.1 What is mailerpy?
    1. mailerpy is 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
    5.2 Gmail App Password
    1. 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.
    5.3 Sending Email using mailerpy
    1. 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.

6. 📅 datetime Library

    6.1 What is datetime Library?
    1. The datetime library 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
    6.2 Common Datetime Formats
    1. %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)
    6.3 datetime Example
    1. 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.4 Common datetime Functions
FunctionDescription
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 - d1Subtracting two dates returns days difference. (d2 - d1).days

7. 🌐 requests Library

    7.1 What is requests?
    1. requests is 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
    7.2 GET Request Example
    1. Example: import requests response = 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.
    7.3 Working with JSON Response
    1. Some websites or APIs return JSON data. Example: import requests response = 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, use response.text instead.
    7.4 Response Details
    1. Example: import requests response = requests.get("https://jsonplaceholder.typicode.com/posts/1")print(response.status_code) print(response.headers) print(response.text)

8. 🍲 BeautifulSoup Library

    8.1 What is BeautifulSoup?
    1. 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 beautifulsoup4 Common methods: - find() - find_all() - select()
    8.2 BeautifulSoup Example
    1. Example: from bs4 import BeautifulSoup import requests response = requests.get("https://example.com")soup = BeautifulSoup(response.text, "html.parser") print(soup.title.text)Output example: Example Domain
    8.3 Finding Elements
    1. 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)

9. 🐼 pandas Library

    9.1 What is pandas?
    1. pandas is 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 pandas Import Code: import pandas as pd
    9.2 Reading CSV using pandas
    1. Example: import pandas as pddf = pd.read_csv("data.csv") print(df.head()) print(df.describe())
    9.3 Filtering Data
    1. 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())
    9.4 Saving Data to CSV
    1. 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=False prevents pandas from adding extra index column in CSV.

10. 📈 matplotlib Library

    10.1 What is matplotlib?
    1. matplotlib is 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
    10.2 Line Plot Example
    1. 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()
    10.3 Scatter Plot Example
    1. 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()

Practice QuestionsNot started

  1. 1. random Library

    Question 1 of 4

      1.1 Practice tasks using random library:
      1. 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}
      2. Modify the guessing game. The user should get three attempts to guess the number. For incorrect guesses, display: Incorrect!! Guess higher number or Incorrect!! Guess lower number depending on the user's guess. If the user cannot guess in three attempts, display: You Lose. Number was {num}
      3. Create a Rock, Paper, Scissors game. The computer randomly chooses one option. Ask the user for input. Display You Win, You Lose, or Draw depending on the game logic. Ask the user whether they want to replay.
      4. 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 word and 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}
  2. 2. random, mailerpy, and os

    Question 2 of 4

      2.1 Practice tasks combining random, mailerpy, and os libraries:
      1. Write a function shuffle_for_flash_game that takes num_of_player as input. It should return shuffled cards in this form: [{"p1": ["c1", "c2", "c3"]}, {"p2": ["c4", "c5", "c6"]}]. Use random library.
      2. 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.
      3. Create a folder all_doc. Inside it, manually create multiple Python files and document files (.py, .doc, .docx, .txt). Write a program that creates folders python_files and doc_files, moves Python files into python_files, moves document files into doc_files, and displays the number of files moved to each folder.
      4. 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}]
  3. 3. math and datetime

    Question 3 of 4

      3.1 Practice tasks using math and datetime libraries:
      1. Find HCF and LCM of a list of numbers using math library. Example: numbers = [12, 18, 24]
      2. Calculate factorial of a number using math library. Example: num = 5
      3. 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.
      4. 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.
      5. Create a program that takes two dates as input and calculates difference between them in years.
  4. 4. requests, BeautifulSoup, pandas, matplotlib, and mailerpy

    Question 4 of 4

      4.1 Practice tasks combining requests, BeautifulSoup, pandas, matplotlib, and mailerpy:
      1. 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 subject Share Data for {date} and body Data scraped from {url}. Keep yourself in cc. 📌 Make sure the website allows scraping before scraping data.
      2. Load the scraped CSV data using pandas. Filter companies where LTP is between 500 and 5000. Save filtered data as filtered_share_data.csv.
      3. Load scraped data and create a scatter plot of LTP and Volume. Use matplotlib.