1. Introduction to Python
What is Python?
Python is a high-level, interpreted programming language known for its simplicity and readability. Created by Guido van Rossum and first released in 1991, Python has become one of the most popular programming languages in the world.
Why Learn Python?
- Easy to Learn: Python has a simple syntax that resembles natural language
- Versatile: Used in web development, data science, AI, automation, and more
- Large Community: Extensive libraries and active support community
- High Demand: One of the most sought-after skills in the job market
Installing Python
Step-by-step Installation:
- Visit python.org
- Download the latest version for your operating system
- Run the installer (check "Add Python to PATH" on Windows)
- Verify installation by opening terminal/command prompt and typing:
python --version
2. Python Basics
Your First Python Program
Let's start with the traditional "Hello, World!" program:
print("Hello, World!")
💡 Tip: The print() function displays output to the screen. It's one of the most commonly used functions in Python.
Python Syntax Rules
- Indentation: Python uses indentation to define code blocks (usually 4 spaces)
- Case Sensitive:
variable and Variable are different
- Comments: Use # for single-line comments, ''' or """ for multi-line
print("Code with proper indentation")
3. Data Types and Variables
Variables
Variables are containers for storing data. In Python, you don't need to declare variable types explicitly.
name = "Pascal"
age = 25
height = 1.75
is_teacher = True
print(name)
print(age)
Basic Data Types
| Data Type |
Description |
Example |
| int |
Integer numbers |
42, -10, 0 |
| float |
Decimal numbers |
3.14, -0.5, 2.0 |
| str |
Text/String |
"Hello", 'Python' |
| bool |
Boolean (True/False) |
True, False |
Type Conversion
x = "10"
y = int(x)
z = float(y)
w = str(z)
print(type(x))
print(type(y))
Getting User Input
name = input("Enter your name: ")
print(f"Hello, {name}!")
age = int(input("Enter your age: "))
print(f"You are {age} years old")
4. Operators
Arithmetic Operators
a = 10
b = 3
print(a + b)
print(a - b)
print(a * b)
print(a / b)
print(a // b)
print(a % b)
print(a ** b)
Comparison Operators
x = 5
y = 10
print(x == y)
print(x != y)
print(x < y)
print(x > y)
print(x <= y)
print(x >= y)
Logical Operators
a = True
b = False
print(a and b)
print(a or b)
print(not a)
5. Control Flow
If-Elif-Else Statements
Conditional statements allow your program to make decisions.
age = 18
if age >= 18:
print("You are an adult")
elif age >= 13:
print("You are a teenager")
else:
print("You are a child")
Example: Grade Calculator
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Your grade is: {grade}")
For Loops
For loops are used to iterate over sequences (lists, strings, ranges, etc.).
for i in range(5):
print(i)
for letter in "Python":
print(letter)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
While Loops
While loops continue executing as long as a condition is true.
count = 0
while count < 5:
print(count)
count += 1
while True:
answer = input("Type 'exit' to quit: ")
if answer == "exit":
break
print(f"You typed: {answer}")
💡 Loop Control Statements:
break - Exit the loop completely
continue - Skip to the next iteration
pass - Do nothing (placeholder)
🏋️ Exercise:
Write a program that prints all even numbers from 1 to 20 using a for loop.
6. Functions
Defining Functions
Functions are reusable blocks of code that perform specific tasks.
def greet():
print("Hello, World!")
greet()
Functions with Parameters
def greet_person(name):
print(f"Hello, {name}!")
greet_person("Pascal")
def add_numbers(a, b):
result = a + b
print(f"{a} + {b} = {result}")
add_numbers(5, 3)
Return Values
def multiply(x, y):
return x * y
result = multiply(4, 5)
print(result)
def calculate(a, b):
sum_result = a + b
diff_result = a - b
return sum_result, diff_result
total, difference = calculate(10, 3)
print(f"Sum: {total}, Difference: {difference}")
Default Parameters
def power(base, exponent=2):
return base ** exponent
print(power(5))
print(power(5, 3))
Example: Calculator Function
def calculator(num1, num2, operation):
if operation == "add":
return num1 + num2
elif operation == "subtract":
return num1 - num2
elif operation == "multiply":
return num1 * num2
elif operation == "divide":
if num2 != 0:
return num1 / num2
else:
return "Error: Division by zero"
else:
return "Invalid operation"
print(calculator(10, 5, "add"))
print(calculator(10, 5, "multiply"))
7. Data Structures
Lists
Lists are ordered, mutable collections that can contain items of different types.
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", 3.14, True]
print(fruits[0])
print(fruits[-1])
fruits[1] = "blueberry"
fruits.append("orange")
fruits.insert(0, "mango")
fruits.remove("apple")
last = fruits.pop()
print(len(fruits))
print("mango" in fruits)
List Slicing
numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
print(numbers[2:5])
print(numbers[:5])
print(numbers[5:])
print(numbers[::2])
print(numbers[::-1])
Tuples
Tuples are ordered, immutable collections.
coordinates = (10, 20)
person = ("Pascal", 25, "Teacher")
print(coordinates[0])
name, age, profession = person
print(f"{name} is {age} years old")
Dictionaries
Dictionaries store key-value pairs. They are unordered, mutable collections that allow fast lookup by key.
student = {
"name": "Pascal",
"age": 25,
"course": "Python Programming"
}
print(student["name"])
print(student.get("age"))
student["grade"] = "A"
student["age"] = 26
del student["grade"]
removed_value = student.pop("age")
print(student.keys())
print(student.values())
print(student.items())
for key, value in student.items():
print(f"{key}: {value}")
Sets
Sets are unordered collections of unique elements. They're useful for removing duplicates and performing mathematical set operations.
fruits = {"apple", "banana", "cherry"}
numbers = set([1, 2, 2, 3, 3, 4])
fruits.add("orange")
fruits.remove("apple")
set1 = {1, 2, 3, 4}
set2 = {3, 4, 5, 6}
print(set1.union(set2))
print(set1.intersection(set2))
print(set1.difference(set2))
🏋️ Exercise:
Create a dictionary to store information about 3 books (title, author, year). Then write a loop to print all book information.
8. Object-Oriented Programming (OOP)
What is OOP?
Object-Oriented Programming is a programming paradigm that organizes code into objects that contain both data (attributes) and functions (methods). OOP helps create more organized, reusable, and maintainable code.
💡 Key OOP Concepts:
- Class: A blueprint for creating objects
- Object: An instance of a class
- Encapsulation: Bundling data and methods together
- Inheritance: Creating new classes from existing ones
- Polymorphism: Using a single interface for different types
Creating Classes and Objects
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def introduce(self):
print(f"Hello, my name is {self.name} and I'm {self.age} years old.")
def birthday(self):
self.age += 1
print(f"Happy birthday! You are now {self.age} years old.")
person1 = Person("Pascal", 25)
person2 = Person("Alice", 30)
person1.introduce()
person1.birthday()
Class Attributes vs Instance Attributes
class Student:
school_name = "Python Academy"
def __init__(self, name, grade):
self.name = name
self.grade = grade
student1 = Student("John", "A")
student2 = Student("Mary", "B")
print(student1.school_name)
print(student2.school_name)
print(student1.name)
print(student2.name)
Inheritance
Inheritance allows a class to inherit attributes and methods from another class. This promotes code reuse and creates hierarchical relationships.
class Animal:
def __init__(self, name, species):
self.name = name
self.species = species
def make_sound(self):
print("Some generic animal sound")
def info(self):
print(f"{self.name} is a {self.species}")
class Dog(Animal):
def __init__(self, name, breed):
super().__init__(name, "Dog")
self.breed = breed
def make_sound(self):
print("Woof! Woof!")
def fetch(self):
print(f"{self.name} is fetching the ball!")
class Cat(Animal):
def __init__(self, name, color):
super().__init__(name, "Cat")
self.color = color
def make_sound(self):
print("Meow!")
dog = Dog("Buddy", "Golden Retriever")
cat = Cat("Whiskers", "Orange")
dog.info()
dog.make_sound()
dog.fetch()
cat.info()
cat.make_sound()
Encapsulation (Private Attributes)
Encapsulation hides internal details and protects data from direct access. In Python, we use naming conventions to indicate private attributes.
class BankAccount:
def __init__(self, owner, balance=0):
self.owner = owner
self.__balance = balance
def get_balance(self):
return self.__balance
def deposit(self, amount):
if amount > 0:
self.__balance += amount
print(f"Deposited ${amount}. New balance: ${self.__balance}")
else:
print("Invalid amount")
def withdraw(self, amount):
if 0 < amount <= self.__balance:
self.__balance -= amount
print(f"Withdrew ${amount}. New balance: ${self.__balance}")
else:
print("Insufficient funds or invalid amount")
account = BankAccount("Pascal", 1000)
account.deposit(500)
account.withdraw(200)
print(account.get_balance())
Real-World Example: Library Management System
class Book:
def __init__(self, title, author, isbn):
self.title = title
self.author = author
self.isbn = isbn
self.is_available = True
def display_info(self):
status = "Available" if self.is_available else "Checked Out"
print(f"'{self.title}' by {self.author} - {status}")
class Library:
def __init__(self, name):
self.name = name
self.books = []
def add_book(self, book):
self.books.append(book)
print(f"Added '{book.title}' to the library")
def checkout_book(self, isbn):
for book in self.books:
if book.isbn == isbn and book.is_available:
book.is_available = False
print(f"Checked out: {book.title}")
return
print("Book not available")
def list_available_books(self):
print(f"\nAvailable books in {self.name}:")
for book in self.books:
if book.is_available:
book.display_info()
library = Library("City Library")
book1 = Book("Python Basics", "John Doe", "001")
book2 = Book("Data Science", "Jane Smith", "002")
library.add_book(book1)
library.add_book(book2)
library.list_available_books()
library.checkout_book("001")
library.list_available_books()
🏋️ Exercise:
Create a Rectangle class with attributes for length and width. Include methods to calculate area and perimeter. Then create a Square class that inherits from Rectangle.
9. File Handling
Why File Handling?
File handling allows programs to store and retrieve data permanently. You can read configuration files, save user data, process logs, and work with various file formats.
Reading Files
file = open("example.txt", "r")
content = file.read()
print(content)
file.close()
with open("example.txt", "r") as file:
content = file.read()
print(content)
with open("example.txt", "r") as file:
for line in file:
print(line.strip())
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)
Writing to Files
with open("output.txt", "w") as file:
file.write("Hello, World!\n")
file.write("This is a new line.\n")
with open("output.txt", "a") as file:
file.write("This line is appended.\n")
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
with open("output.txt", "w") as file:
file.writelines(lines)
💡 File Modes:
'r' - Read (default) - Error if file doesn't exist
'w' - Write - Creates new file or overwrites existing
'a' - Append - Adds to end of file
'r+' - Read and write
'b' - Binary mode (e.g., 'rb', 'wb')
Working with CSV Files
CSV (Comma-Separated Values) files are commonly used for storing tabular data.
import csv
data = [
["Name", "Age", "City"],
["Pascal", 25, "Kigali"],
["Alice", 30, "Nairobi"],
["Bob", 35, "Lagos"]
]
with open("people.csv", "w", newline="") as file:
writer = csv.writer(file)
writer.writerows(data)
with open("people.csv", "r") as file:
reader = csv.reader(file)
for row in reader:
print(row)
with open("people.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
print(f"{row['Name']} is {row['Age']} years old")
Working with JSON Files
JSON (JavaScript Object Notation) is widely used for storing and exchanging structured data.
import json
student_data = {
"name": "Pascal",
"age": 25,
"courses": ["Python", "Data Science", "Web Development"],
"grades": {"Python": "A", "Math": "B"}
}
with open("student.json", "w") as file:
json.dump(student_data, file, indent=4)
with open("student.json", "r") as file:
loaded_data = json.load(file)
print(loaded_data["name"])
print(loaded_data["courses"])
Checking if File Exists
import os
if os.path.exists("example.txt"):
print("File exists!")
else:
print("File not found!")
file_size = os.path.getsize("example.txt")
print(f"File size: {file_size} bytes")
if os.path.exists("temp.txt"):
os.remove("temp.txt")
print("File deleted")
🏋️ Exercise:
Create a program that reads a text file, counts the number of words, and writes the count to a new file called "word_count.txt".
10. Modules and Packages
What are Modules?
A module is a file containing Python code (functions, classes, variables) that you can reuse in other programs. Modules help organize code and promote reusability.
Importing Modules
import math
print(math.pi)
print(math.sqrt(16))
from math import pi, sqrt
print(pi)
print(sqrt(25))
import math as m
print(m.ceil(4.3))
from math import *
print(floor(4.7))
Commonly Used Built-in Modules
1. Math Module
import math
print(math.sqrt(16))
print(math.pow(2, 3))
print(math.ceil(4.3))
print(math.floor(4.7))
print(math.factorial(5))
print(math.sin(math.pi/2))
2. Random Module
import random
print(random.randint(1, 10))
print(random.random())
colors = ["red", "blue", "green"]
print(random.choice(colors))
numbers = [1, 2, 3, 4, 5]
random.shuffle(numbers)
print(numbers)
print(random.sample([1, 2, 3, 4, 5], 3))
3. Datetime Module
from datetime import datetime, timedelta
now = datetime.now()
print(now)
print(f"Year: {now.year}, Month: {now.month}, Day: {now.day}")
print(now.strftime("%Y-%m-%d"))
print(now.strftime("%B %d, %Y"))
print(now.strftime("%I:%M %p"))
tomorrow = now + timedelta(days=1)
next_week = now + timedelta(weeks=1)
print(f"Tomorrow: {tomorrow.strftime('%Y-%m-%d')}")
4. OS Module
import os
print(os.getcwd())
print(os.listdir("."))
os.mkdir("new_folder")
print(os.path.exists("file.txt"))
path = "documents/report.pdf"
print(os.path.basename(path))
print(os.path.dirname(path))
Creating Your Own Module
You can create your own modules by saving Python code in a .py file.
Example: Creating a Math Utilities Module
File: math_utils.py
def square(n):
"""Returns the square of a number"""
return n ** 2
def cube(n):
"""Returns the cube of a number"""
return n ** 3
def is_even(n):
"""Checks if a number is even"""
return n % 2 == 0
PI = 3.14159
Using the module in another file:
import math_utils
print(math_utils.square(5))
print(math_utils.cube(3))
print(math_utils.is_even(4))
print(math_utils.PI)
Installing External Packages
Python has thousands of third-party packages available through pip (Python Package Installer).
pip install requests
pip install requests==2.28.0
pip install --upgrade requests
pip uninstall requests
pip list
💡 Popular Python Packages:
- requests - HTTP library for making web requests
- numpy - Numerical computing with arrays
- pandas - Data analysis and manipulation
- matplotlib - Data visualization and plotting
- flask/django - Web development frameworks
- beautifulsoup4 - Web scraping
- pillow - Image processing
11. Error Handling
Understanding Errors
Errors (exceptions) are problems that occur during program execution. Python provides mechanisms to catch and handle these errors gracefully instead of crashing your program.
Common Error Types
| Error Type |
Description |
Example |
| SyntaxError |
Invalid Python syntax |
Missing colon, wrong indentation |
| NameError |
Variable not defined |
Using undefined variable |
| TypeError |
Wrong type of operation |
"hello" + 5 |
| ValueError |
Correct type, wrong value |
int("abc") |
| ZeroDivisionError |
Division by zero |
10 / 0 |
| FileNotFoundError |
File doesn't exist |
open("nonexistent.txt") |
| IndexError |
Index out of range |
list[10] when list has 5 items |
| KeyError |
Key not in dictionary |
dict["missing_key"] |
Try-Except Blocks
The try-except statement allows you to handle errors without crashing your program.
try:
number = int(input("Enter a number: "))
result = 100 / number
print(f"Result: {result}")
except:
print("An error occurred!")
Catching Specific Exceptions
It's better to catch specific exceptions so you can handle different errors appropriately.
try:
number = int(input("Enter a number: "))
result = 100 / number
print(f"Result: {result}")
except ValueError:
print("Invalid input! Please enter a valid number.")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An unexpected error occurred: {e}")
Try-Except-Else-Finally
try:
file = open("data.txt", "r")
content = file.read()
except FileNotFoundError:
print("File not found!")
except Exception as e:
print(f"Error reading file: {e}")
else:
print("File read successfully!")
print(content)
finally:
try:
file.close()
print("File closed.")
except:
pass
💡 Error Handling Best Practices:
- Catch specific exceptions, not generic
except: blocks
- Use
finally for cleanup code (closing files, database connections)
- Don't silence errors - log or handle them appropriately
- Use exceptions for exceptional cases, not normal flow control
Raising Exceptions
You can raise your own exceptions using the raise keyword.
def check_age(age):
if age < 0:
raise ValueError("Age cannot be negative!")
elif age < 18:
raise Exception("You must be 18 or older")
else:
print("Age is valid")
try:
check_age(-5)
except ValueError as e:
print(f"Error: {e}")
Real-World Example: Robust Input Validation
def get_valid_number(prompt, min_value=None, max_value=None):
"""Get a valid number from user with optional range validation"""
while True:
try:
number = float(input(prompt))
if min_value is not None and number < min_value:
print(f"Number must be at least {min_value}")
continue
if max_value is not None and number > max_value:
print(f"Number must be at most {max_value}")
continue
return number
except ValueError:
print("Invalid input! Please enter a valid number.")
age = get_valid_number("Enter your age (0-120): ", 0, 120)
print(f"Your age is: {age}")
🏋️ Exercise:
Write a program that asks the user for two numbers and an operation (+, -, *, /). Use try-except to handle invalid inputs and division by zero errors.
12. Advanced Topics
List Comprehensions
List comprehensions provide a concise way to create lists based on existing lists or ranges.
squares = []
for i in range(10):
squares.append(i ** 2)
squares = [i ** 2 for i in range(10)]
print(squares)
even_squares = [i ** 2 for i in range(10) if i % 2 == 0]
print(even_squares)
names = ["pascal", "alice", "bob"]
capitalized = [name.capitalize() for name in names]
print(capitalized)
matrix = [[i*j for j in range(3)] for i in range(3)]
print(matrix)
Dictionary and Set Comprehensions
squares_dict = {i: i**2 for i in range(6)}
print(squares_dict)
unique_lengths = {len(word) for word in ["apple", "pie", "banana"]}
print(unique_lengths)
Lambda Functions
Lambda functions are small, anonymous functions defined inline. They're useful for short, simple operations.
def square(x):
return x ** 2
square = lambda x: x ** 2
print(square(5))
add = lambda x, y: x + y
print(add(3, 4))
numbers = [1, 2, 3, 4, 5]
squared = list(map(lambda x: x**2, numbers))
print(squared)
even_numbers = list(filter(lambda x: x % 2 == 0, numbers))
print(even_numbers)
Map, Filter, and Reduce
from functools import reduce
numbers = [1, 2, 3, 4, 5]
doubled = list(map(lambda x: x * 2, numbers))
print(doubled)
evens = list(filter(lambda x: x % 2 == 0, numbers))
print(evens)
total = reduce(lambda x, y: x + y, numbers)
print(total)
product = reduce(lambda x, y: x * y, numbers)
print(product)
Decorators
Decorators are a way to modify or enhance functions without changing their code. They "wrap" a function with additional functionality.
def uppercase_decorator(func):
def wrapper():
result = func()
return result.upper()
return wrapper
@uppercase_decorator
def greet():
return "hello"
print(greet())
import time
def timer_decorator(func):
def wrapper(*args, **kwargs):
start = time.