Welcome to Python Libraries

Learn built-in and popular third‑party libraries, installing packages, and quick intros to Matplotlib, Pandas, and NumPy.

Python libraries overview

📚 Python Libraries

Learning Objectives:

By the end of this lesson, learners should be able to:

  • Understand what a Python library is.
  • Know how to install and import a library.
  • Use popular libraries like math, random, and datetime with simple examples.
  • Practice with short, fun tasks using these libraries.

What is a Python Library?

A Python library is a collection of pre-written code that you can use to perform common tasks without having to write everything from scratch. Think of it like a toolbox — instead of making your own hammer, you just pull one out from the toolbox! 🛠️

How to Use a Library in Python

1. Importing a Built-in Library:

import math
print(math.sqrt(16)) # Output: 4.0
print(math.pi) # Output: 3.141592653589793

2. Importing Part of a Library:

from math import sqrt, sin, radians, pow
print("Square root of 36:", sqrt(36))
print("Sine of 90 degrees:", sin(radians(90)))
print("Power of 2^3:", pow(2,3))

3. random – Generate random numbers:

import random
print("Random number between 1 and 10:", random.randint(1, 10))
print("Random choice from a list:", random.choice(['apple', 'banana', 'cherry']))

4. datetime – Work with dates and time:

import datetime
today = datetime.date.today()
print("Today's date is:", today)
now = datetime.datetime.now()
print("Current time:", now.strftime("%H:%M:%S"))

📦 Python Standard Library & Popular Extra Libraries

Python Standard Library:

The Python Standard Library is a collection of built-in modules that come with Python. These modules help you perform common tasks like reading files, working with dates, or handling math — without installing anything extra.

Popular Extra Python Libraries:

  • TensorFlow – For machine learning and deep learning.
  • Matplotlib – For creating charts and graphs.
  • Pandas – For handling and analyzing data.
  • NumPy – For working with numbers and large arrays.
  • SciPy – For scientific and technical computing.
  • Scrapy – For web scraping (getting data from websites).
  • Scikit-learn – For machine learning (predictions and classifications).
  • PyGame – For building games with graphics and sound.
  • PyTorch – For deep learning and neural networks.
  • PyBrain – For beginners in machine learning and AI.

There are many more Python libraries available. Choosing the right library can make development faster and easier. Python libraries play a crucial role and are very helpful to developers. 💻

📦 Installing Python Packages – Simple Summary

Python has lots of built-in tools (standard library), but sometimes you'll need more. That’s where third-party packages come in — extra tools made by the community.

pip

  • pip is Python’s tool for installing packages.
  • It stands for "Pip Installs Packages".
  • If you’re using Python 3.4 or newer, you already have pip3.
  • To install a package, just run: pip install package_name

PyPI

  • PyPI (Python Package Index) is the place where all these third-party packages live.
  • pip automatically pulls packages from PyPI.
  • You can also visit pypi.org to search for packages manually.

Popular Third-party Libraries

  • requests, scrapy, Twisted
  • Pillow, lxml, PyYAML
  • Django, Flask, Pyramid
  • SQLAlchemy, six

Go-to packages for common tasks:

  • numpy, scipy, pandas
  • pytest, tox, coverage, mock
  • Jinja2
  • cryptography
  • pylint, flake8, pep8
  • pymongo, redis, MySQL-Python, psycopg2

Resources:

📊 Data Visualization with Matplotlib

What is Matplotlib?

Matplotlib is a library that allows you to create visual representations of your data. It’s especially useful when working with data in Pandas or NumPy.

Installing Matplotlib:

pip install matplotlib

Basic Line Plot:

import matplotlib.pyplot as plt
x = [1, 2, 3, 4, 5]
y = [10, 20, 25, 30, 40]
plt.plot(x, y)
plt.title("Simple Line Plot")
plt.xlabel("X-axis")
plt.ylabel("Y-axis")
plt.show()

Bar Chart Example:

names = ['Alice', 'Bob', 'Charlie']
scores = [85, 90, 78]
plt.bar(names, scores, color='skyblue')
plt.title("Student Scores")
plt.xlabel("Students")
plt.ylabel("Scores")
plt.show()

Pie Chart Example:

activities = ['Sleeping', 'Eating', 'Coding', 'Gaming']
hours = [8, 2, 8, 6]
plt.pie(hours, labels=activities, autopct='%1.1f%%')
plt.title("Daily Activities")
plt.show()

Histogram Example:

ages = [22, 21, 20, 23, 24, 22, 20, 21, 22, 25, 23]
plt.hist(ages, bins=5, color='purple')
plt.title("Age Distribution")
plt.xlabel("Age")
plt.ylabel("Frequency")
plt.show()

Combine with Pandas Example:

import pandas as pd
data = {'Year': [2021, 2022, 2023], 'Users': [1500, 3000, 5000]}
df = pd.DataFrame(data)
plt.plot(df['Year'], df['Users'], marker='o')
plt.title("User Growth Over Time")
plt.xlabel("Year")
plt.ylabel("Users")
plt.grid(True)
plt.show()

Practice Tasks:

  • Create a bar chart showing 5 different countries and their population.
  • Create a pie chart showing how a student spends 24 hours of their day.
  • Make a line chart that shows temperature changes during the day (morning, noon, evening, night).

🐼 What is Pandas?

Pandas is used for data manipulation and analysis. It allows you to:

  • Work with tables (just like Excel or Google Sheets!)
  • Clean and filter data easily
  • Read from CSV, Excel, JSON, etc.

Installing Pandas:

pip install pandas

Basic Pandas Example:

import pandas as pd

# Create a DataFrame (table-like structure)
data = {
  'Name': ['Alice', 'Bob', 'Charlie'],
  'Age': [24, 30, 22],
  'Score': [85, 90, 95]
}

df = pd.DataFrame(data)

print(df)

# Access column
print("Names:", df['Name'])

# Filter rows
print("Scores above 90:")
print(df[df['Score'] > 90])

Reading CSV Files with Pandas:

df = pd.read_csv('students.csv')
print(df.head()) # Show first 5 rows

Practice Task (Pandas):

  • Create a DataFrame with 3 students: name, age, and grade.
  • Add a column called “Passed” where grade > 50 = True.
  • Filter and display only students who passed.

🔢 What is NumPy?

NumPy stands for Numerical Python. It’s used for:

  • Working with large arrays and matrices
  • Performing math operations on arrays

Installing NumPy:

pip install numpy

Basic NumPy Example:

import numpy as np

# Create a simple array
my_array = np.array([1, 2, 3, 4, 5])
print("Array:", my_array)

# Perform operations
print("Array * 2:", my_array * 2) # Multiply each element by 2
print("Mean:", np.mean(my_array)) # Average of the array
print("Square Roots:", np.sqrt(my_array))

Practice Task (NumPy):

  • Create an array with numbers 10 to 50.
  • Find the maximum and minimum values.
  • Multiply all elements by 3.