🐍 Python Learning Guide

From Beginner to Expert

A comprehensive guide to mastering Python programming with clear explanations, practical examples, and hands-on exercises.

IT Teacher Pascal NSENGIMANA
print('Hello, world!')

📚 Table of Contents

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?

Installing Python

Step-by-step Installation:

  1. Visit python.org
  2. Download the latest version for your operating system
  3. Run the installer (check "Add Python to PATH" on Windows)
  4. 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

# This is a single-line comment """ This is a multi-line comment """ 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.

# Creating variables name = "Pascal" age = 25 height = 1.75 is_teacher = True print(name) # Output: Pascal print(age) # Output: 25

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

# Converting between types x = "10" y = int(x) # Convert string to integer z = float(y) # Convert integer to float w = str(z) # Convert float to string print(type(x)) # Output: <class 'str'> print(type(y)) # Output: <class 'int'>

Getting User Input

# Getting input from user 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

# Basic arithmetic a = 10 b = 3 print(a + b) # Addition: 13 print(a - b) # Subtraction: 7 print(a * b) # Multiplication: 30 print(a / b) # Division: 3.333... print(a // b) # Floor division: 3 print(a % b) # Modulus (remainder): 1 print(a ** b) # Exponentiation: 1000

Comparison Operators

x = 5 y = 10 print(x == y) # Equal to: False print(x != y) # Not equal to: True print(x < y) # Less than: True print(x > y) # Greater than: False print(x <= y) # Less than or equal: True print(x >= y) # Greater than or equal: False

Logical Operators

# Logical AND, OR, NOT a = True b = False print(a and b) # False print(a or b) # True print(not a) # False

5. Control Flow

If-Elif-Else Statements

Conditional statements allow your program to make decisions.

# Simple if statement 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.).

# Loop through a range for i in range(5): print(i) # Prints 0, 1, 2, 3, 4 # Loop through a string for letter in "Python": print(letter) # Loop through a list fruits = ["apple", "banana", "cherry"] for fruit in fruits: print(fruit)

While Loops

While loops continue executing as long as a condition is true.

# Basic while loop count = 0 while count < 5: print(count) count += 1 # While loop with break 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.

# Basic function def greet(): print("Hello, World!") greet() # Call the function

Functions with Parameters

# Function with parameters def greet_person(name): print(f"Hello, {name}!") greet_person("Pascal") # Output: Hello, Pascal! # Function with multiple parameters def add_numbers(a, b): result = a + b print(f"{a} + {b} = {result}") add_numbers(5, 3) # Output: 5 + 3 = 8

Return Values

# Function that returns a value def multiply(x, y): return x * y result = multiply(4, 5) print(result) # Output: 20 # Function with multiple return values 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)) # Output: 25 (5^2) print(power(5, 3)) # Output: 125 (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")) # Output: 15 print(calculator(10, 5, "multiply")) # Output: 50

7. Data Structures

Lists

Lists are ordered, mutable collections that can contain items of different types.

# Creating lists fruits = ["apple", "banana", "cherry"] numbers = [1, 2, 3, 4, 5] mixed = [1, "hello", 3.14, True] # Accessing elements print(fruits[0]) # First element: apple print(fruits[-1]) # Last element: cherry # Modifying lists fruits[1] = "blueberry" fruits.append("orange") # Add to end fruits.insert(0, "mango") # Insert at position fruits.remove("apple") # Remove specific item last = fruits.pop() # Remove and return last item # List operations print(len(fruits)) # Length of list print("mango" in fruits) # Check if item exists

List Slicing

numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] print(numbers[2:5]) # Elements 2-4: [2, 3, 4] print(numbers[:5]) # First 5 elements print(numbers[5:]) # From index 5 to end print(numbers[::2]) # Every 2nd element print(numbers[::-1]) # Reverse the list

Tuples

Tuples are ordered, immutable collections.

# Creating tuples coordinates = (10, 20) person = ("Pascal", 25, "Teacher") # Accessing elements print(coordinates[0]) # Output: 10 # Unpacking tuples 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.

# Creating dictionaries student = { "name": "Pascal", "age": 25, "course": "Python Programming" } # Accessing values print(student["name"]) # Output: Pascal print(student.get("age")) # Output: 25 # Adding/Modifying entries student["grade"] = "A" # Add new key-value student["age"] = 26 # Update existing value # Removing entries del student["grade"] # Remove key-value pair removed_value = student.pop("age") # Remove and return value # Dictionary methods print(student.keys()) # Get all keys print(student.values()) # Get all values print(student.items()) # Get key-value pairs # Looping through dictionary 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.

# Creating sets fruits = {"apple", "banana", "cherry"} numbers = set([1, 2, 2, 3, 3, 4]) # Removes duplicates: {1, 2, 3, 4} # Set operations fruits.add("orange") # Add element fruits.remove("apple") # Remove element # Set mathematics set1 = {1, 2, 3, 4} set2 = {3, 4, 5, 6} print(set1.union(set2)) # Union: {1, 2, 3, 4, 5, 6} print(set1.intersection(set2)) # Intersection: {3, 4} print(set1.difference(set2)) # Difference: {1, 2}

🏋️ 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

# Define a class class Person: # Constructor method (initializer) def __init__(self, name, age): self.name = name # Instance attribute self.age = age # Instance attribute # Instance method def introduce(self): print(f"Hello, my name is {self.name} and I'm {self.age} years old.") # Another method def birthday(self): self.age += 1 print(f"Happy birthday! You are now {self.age} years old.") # Create objects (instances) person1 = Person("Pascal", 25) person2 = Person("Alice", 30) # Call methods person1.introduce() # Output: Hello, my name is Pascal and I'm 25 years old. person1.birthday() # Output: Happy birthday! You are now 26 years old.

Class Attributes vs Instance Attributes

class Student: # Class attribute (shared by all instances) school_name = "Python Academy" def __init__(self, name, grade): # Instance attributes (unique to each instance) self.name = name self.grade = grade student1 = Student("John", "A") student2 = Student("Mary", "B") print(student1.school_name) # Output: Python Academy print(student2.school_name) # Output: Python Academy print(student1.name) # Output: John print(student2.name) # Output: Mary

Inheritance

Inheritance allows a class to inherit attributes and methods from another class. This promotes code reuse and creates hierarchical relationships.

# Parent class (Base class) 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}") # Child class (Derived class) class Dog(Animal): def __init__(self, name, breed): super().__init__(name, "Dog") # Call parent constructor self.breed = breed # Override parent method def make_sound(self): print("Woof! Woof!") # Add new method 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!") # Create instances dog = Dog("Buddy", "Golden Retriever") cat = Cat("Whiskers", "Orange") dog.info() # Output: Buddy is a Dog dog.make_sound() # Output: Woof! Woof! dog.fetch() # Output: Buddy is fetching the ball! cat.info() # Output: Whiskers is a Cat cat.make_sound() # Output: Meow!

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 # Private attribute (double underscore) # Getter method def get_balance(self): return self.__balance # Methods to modify balance safely 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) # Output: Deposited $500. New balance: $1500 account.withdraw(200) # Output: Withdrew $200. New balance: $1300 print(account.get_balance()) # Output: 1300

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() # Using the library system 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

# Method 1: Basic file reading file = open("example.txt", "r") # 'r' = read mode content = file.read() print(content) file.close() # Method 2: Using 'with' statement (recommended) with open("example.txt", "r") as file: content = file.read() print(content) # File automatically closes after the 'with' block # Reading line by line with open("example.txt", "r") as file: for line in file: print(line.strip()) # strip() removes newline characters # Reading all lines into a list with open("example.txt", "r") as file: lines = file.readlines() print(lines)

Writing to Files

# Write mode ('w') - creates new file or overwrites existing with open("output.txt", "w") as file: file.write("Hello, World!\n") file.write("This is a new line.\n") # Append mode ('a') - adds to end of existing file with open("output.txt", "a") as file: file.write("This line is appended.\n") # Writing multiple lines 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 # Writing to 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) # Reading from CSV with open("people.csv", "r") as file: reader = csv.reader(file) for row in reader: print(row) # Using DictReader for better readability 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 # Python dictionary student_data = { "name": "Pascal", "age": 25, "courses": ["Python", "Data Science", "Web Development"], "grades": {"Python": "A", "Math": "B"} } # Write JSON to file with open("student.json", "w") as file: json.dump(student_data, file, indent=4) # indent=4 for pretty printing # Read JSON from file 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 # Check if file exists if os.path.exists("example.txt"): print("File exists!") else: print("File not found!") # Get file size file_size = os.path.getsize("example.txt") print(f"File size: {file_size} bytes") # Delete a file 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

# Method 1: Import entire module import math print(math.pi) # Output: 3.141592653589793 print(math.sqrt(16)) # Output: 4.0 # Method 2: Import specific functions from math import pi, sqrt print(pi) # Output: 3.141592653589793 print(sqrt(25)) # Output: 5.0 # Method 3: Import with alias import math as m print(m.ceil(4.3)) # Output: 5 # Method 4: Import all (not recommended) from math import * print(floor(4.7)) # Output: 4

Commonly Used Built-in Modules

1. Math Module

import math print(math.sqrt(16)) # Square root: 4.0 print(math.pow(2, 3)) # Power: 8.0 print(math.ceil(4.3)) # Round up: 5 print(math.floor(4.7)) # Round down: 4 print(math.factorial(5)) # 5! = 120 print(math.sin(math.pi/2)) # Sine: 1.0

2. Random Module

import random # Random integer between 1 and 10 print(random.randint(1, 10)) # Random float between 0 and 1 print(random.random()) # Choose random item from list colors = ["red", "blue", "green"] print(random.choice(colors)) # Shuffle a list numbers = [1, 2, 3, 4, 5] random.shuffle(numbers) print(numbers) # Random sample without replacement print(random.sample([1, 2, 3, 4, 5], 3))

3. Datetime Module

from datetime import datetime, timedelta # Current date and time now = datetime.now() print(now) print(f"Year: {now.year}, Month: {now.month}, Day: {now.day}") # Format date print(now.strftime("%Y-%m-%d")) # 2026-01-21 print(now.strftime("%B %d, %Y")) # January 21, 2026 print(now.strftime("%I:%M %p")) # 02:30 PM # Date arithmetic tomorrow = now + timedelta(days=1) next_week = now + timedelta(weeks=1) print(f"Tomorrow: {tomorrow.strftime('%Y-%m-%d')}")

4. OS Module

import os # Get current working directory print(os.getcwd()) # List files in directory print(os.listdir(".")) # Create directory os.mkdir("new_folder") # Check if path exists print(os.path.exists("file.txt")) # Get file name and extension path = "documents/report.pdf" print(os.path.basename(path)) # report.pdf print(os.path.dirname(path)) # documents

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

# 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:

# main.py import math_utils print(math_utils.square(5)) # Output: 25 print(math_utils.cube(3)) # Output: 27 print(math_utils.is_even(4)) # Output: True print(math_utils.PI) # Output: 3.14159

Installing External Packages

Python has thousands of third-party packages available through pip (Python Package Installer).

# Install a package (run in terminal/command prompt) pip install requests # Install specific version pip install requests==2.28.0 # Upgrade a package pip install --upgrade requests # Uninstall a package pip uninstall requests # List installed packages 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.

# Basic try-except 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: # Runs if no exception occurred print("File read successfully!") print(content) finally: # Always runs, whether exception occurred or not 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.") # Usage 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.

# Traditional way squares = [] for i in range(10): squares.append(i ** 2) # List comprehension (more concise) squares = [i ** 2 for i in range(10)] print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] # With condition even_squares = [i ** 2 for i in range(10) if i % 2 == 0] print(even_squares) # [0, 4, 16, 36, 64] # String manipulation names = ["pascal", "alice", "bob"] capitalized = [name.capitalize() for name in names] print(capitalized) # ['Pascal', 'Alice', 'Bob'] # Nested list comprehension matrix = [[i*j for j in range(3)] for i in range(3)] print(matrix) # [[0, 0, 0], [0, 1, 2], [0, 2, 4]]

Dictionary and Set Comprehensions

# Dictionary comprehension squares_dict = {i: i**2 for i in range(6)} print(squares_dict) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25} # Set comprehension unique_lengths = {len(word) for word in ["apple", "pie", "banana"]} print(unique_lengths) # {3, 5, 6}

Lambda Functions

Lambda functions are small, anonymous functions defined inline. They're useful for short, simple operations.

# Regular function def square(x): return x ** 2 # Lambda equivalent square = lambda x: x ** 2 print(square(5)) # Output: 25 # Lambda with multiple arguments add = lambda x, y: x + y print(add(3, 4)) # Output: 7 # Using lambda with built-in functions numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, numbers)) print(squared) # [1, 4, 9, 16, 25] even_numbers = list(filter(lambda x: x % 2 == 0, numbers)) print(even_numbers) # [2, 4]

Map, Filter, and Reduce

from functools import reduce numbers = [1, 2, 3, 4, 5] # Map: Apply function to each element doubled = list(map(lambda x: x * 2, numbers)) print(doubled) # [2, 4, 6, 8, 10] # Filter: Keep elements that match condition evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # [2, 4] # Reduce: Combine elements into single value total = reduce(lambda x, y: x + y, numbers) print(total) # 15 (1+2+3+4+5) product = reduce(lambda x, y: x * y, numbers) print(product) # 120 (1*2*3*4*5)

Decorators

Decorators are a way to modify or enhance functions without changing their code. They "wrap" a function with additional functionality.

# Basic decorator def uppercase_decorator(func): def wrapper(): result = func() return result.upper() return wrapper @uppercase_decorator def greet(): return "hello" print(greet()) # Output: HELLO # Decorator with timing functionality import time def timer_decorator(func): def wrapper(*args, **kwargs): start = time.