🐍
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
PYTHON PROGRAMMING
Complete Teaching Notes
From Absolute Beginner to Intermediate Level
Topics: Introduction • Variables • Data Types • Operators • Strings • Lists • Tuples •
Dictionaries • Sets • Control Flow • Loops • Functions • Modules & Libraries
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
SECTION 1 — INTRODUCTION TO PYTHON
Chapter 1: What is Python?
Python is a high-level, easy-to-read programming language created by Guido van Rossum in 1991. It is
one of the most popular programming languages in the world today.
Why Learn Python?
Python reads almost like English, making it perfect for beginners. It is used in web
development, data science, artificial intelligence, automation, and much more.
1.1 What Can Python Do?
• Build websites and web applications
• Analyse and visualise data (Data Science)
• Create Artificial Intelligence (AI) and Machine Learning models
• Automate boring, repetitive tasks
• Develop games and desktop apps
• Work with databases
1.2 Python Characteristics
Feature What it Means
Interpreted Python runs line by line — no need to compile
first
High-Level Easy to read; hides complex computer details
Dynamically Typed You don't need to declare variable types
Object-Oriented Organises code using objects and classes
Open Source Free to use and share by anyone
Cross-Platform Runs on Windows, Mac, and Linux
1.3 Your First Python Program
Let's start with the classic first program — printing a message to the screen:
# This is a comment — Python ignores it
# Comments help explain your code
print("Hello, World!")
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
print("Welcome to Python!")
Output:
Hello, World! Welcome to Python!
💡 print() is a built-in function. Anything inside the quotes gets displayed on screen.
📝[Link] starting with # are comments. They help others (and your future self) understand your
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
SECTION 2 — VARIABLES & DATA TYPES
Chapter 2: Variables
A variable is a container that stores a value in your program. Think of it like a labelled box — you put
something inside and refer to it by name later.
2.1 Creating Variables
In Python, you create a variable simply by assigning a value with the = sign:
# Creating variables
name = "Alice" # String (text)
age = 25 # Integer (whole number)
height = 5.6 # Float (decimal number)
is_student = True # Boolean (True or False)
# Printing variables
print("Name:", name)
print("Age:", age)
print("Height:", height)
print("Is student:", is_student)
Output:
Name: Alice Age: 25 Height: 5.6 Is student: True
2.2 Naming Rules for Variables
• Must start with a letter or underscore (_)
• Cannot start with a number
• Can only contain letters, numbers, and underscores
• Case-sensitive: myName and myname are different!
• Cannot use reserved keywords (like if, for, while, etc.)
# VALID variable names
my_name = 'Bob'
_score = 100
player1 = 'Alice'
totalMarks = 98
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
# INVALID variable names (these cause errors!)
# 2player = 'Alice' -- Cannot start with a number
# my-name = 'Bob' -- Hyphens not allowed
# for = 10 -- 'for' is a reserved keyword
2.3 Multiple Assignment
# Assign the same value to multiple variables
x = y = z = 0
print(x, y, z) # Output: 0 0 0
# Assign different values in one line
a, b, c = 10, 20, 30
print(a, b, c) # Output: 10 20 30
# Swap two variables (Python magic!)
a, b = b, a
print(a, b) # Output: 20 10
Chapter 3: Data Types
Python has several built-in data types. Understanding them is fundamental to programming.
Data Type Description & Example
int Whole numbers: age = 25 count = -5
float Decimal numbers: price = 9.99 pi = 3.14159
str Text (string): name = "Alice" city = "Nairobi"
bool True or False: is_raining = True has_passed = False
list Ordered, changeable: [1, 2, 3] ['a', 'b', 'c']
tuple Ordered, unchangeable: (10, 20, 30)
dict Key-value pairs: {"name": "Alice", "age": 25}
set Unique, unordered: {1, 2, 3, 4}
NoneType No value: result = None
3.1 Checking a Data Type
# Use type() to check the type of any variable
name = "Alice"
age = 25
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
price = 9.99
is_active = True
print(type(name)) # <class "str">
print(type(age)) # <class "int">
print(type(price)) # <class "float">
print(type(is_active)) # <class "bool">
3.2 Type Conversion (Casting)
You can convert between data types using built-in functions:
# Convert string to integer
x = "10"
y = int(x)
print(y + 5) # Output: 15
# Convert integer to string
num = 42
text = str(num)
print("Number: " + text) # Output: Number: 42
# Convert string to float
price = float("3.99")
print(price * 2) # Output: 7.98
# Convert float to integer (removes decimal)
pi = 3.14159
print(int(pi)) # Output: 3
⚠️ int("hello") will cause an error! You can only convert strings that actually contain numbers.
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
SECTION 3 — OPERATORS
Chapter 4: Operators
Operators are symbols that perform operations on values and variables.
4.1 Arithmetic Operators
Operator Meaning & Example
+ Addition: 5 + 3 = 8
- Subtraction: 10 - 4 = 6
* Multiplication: 3 * 4 = 12
/ Division (returns float): 10 / 3 = 3.333...
// Floor Division (whole number): 10 // 3 = 3
% Modulus (remainder): 10 % 3 = 1
** Exponent (power): 2 ** 8 = 256
a = 15
b = 4
print(a + b) # 19
print(a - b) # 11
print(a * b) # 60
print(a / b) # 3.75
print(a // b) # 3 (floor division)
print(a % b) # 3 (remainder)
print(a ** b) # 50625 (15 to the power of 4)
4.2 Comparison Operators
Comparison operators compare two values and return True or False:
Operator Meaning & Example
== Equal to: 5 == 5 → True
!= Not equal to: 5 != 3 → True
> Greater than: 10 > 7 → True
< Less than: 3 < 8 → True
>= Greater than or equal: 5 >= 5 → True
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
<= Less than or equal: 4 <= 9 → True
4.3 Logical Operators
Operator Meaning & Example
and Both conditions must be True: 5 > 2 and 10 > 1 → True
or At least one condition is True: 5 > 10 or 3 > 1 → True
not Reverses the result: not True → False
age = 20
has_id = True
# Check both conditions
print(age >= 18 and has_id) # True
# Check at least one
print(age >= 18 or has_id) # True
# Reverse
print(not has_id) # False
4.4 Assignment Operators
Operator Equivalent To
x = 10 Assign 10 to x
x += 5 x = x + 5 → x becomes 15
x -= 3 x = x - 3 → x becomes 7
x *= 2 x = x * 2 → x becomes 20
x /= 4 x = x / 4 → x becomes 2.5
x **= 2 x = x ** 2 → x becomes 100
x //= 3 x = x // 3 → x becomes 3
x %= 3 x = x % 3 → x becomes 1
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
SECTION 4 — STRINGS
Chapter 5: Strings
A string is a sequence of characters enclosed in single or double quotes. Strings are one of the most
commonly used data types in Python.
5.1 Creating Strings
# Single quotes
name = 'Alice'
# Double quotes
city = "Nairobi"
# Triple quotes — for multi-line strings
message = """Hello,
This is a multi-line
string in Python!"""
print(name, city)
print(message)
5.2 String Operations
# Concatenation — joining strings
first = "Hello"
second = "World"
full = first + " " + second
print(full) # Hello World
# Repetition — repeat a string
stars = "* " * 5
print(stars) # * * * * *
# Length — count characters
word = "Python"
print(len(word)) # 6
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
5.3 String Indexing & Slicing
Each character in a string has an index (position). Indexing starts at 0!
text = "Python"
# P y t h o n
# 0 1 2 3 4 5 (positive index)
# -6 -5 -4 -3 -2 -1 (negative index)
print(text[0]) # P (first character)
print(text[-1]) # n (last character)
print(text[1:4]) # yth (slice: index 1 to 3)
print(text[:3]) # Pyt (start to index 2)
print(text[3:]) # hon (index 3 to end)
print(text[::2]) # Pto (every 2nd character)
print(text[::-1]) # nohtyP (reverse!)
5.4 Useful String Methods
Method What it Does & Example
upper() "hello".upper() → "HELLO"
lower() "HELLO".lower() → "hello"
title() "hello world".title() → "Hello World"
strip() " hello ".strip() → "hello"
replace(a, b) "Hello".replace("H", "J") → "Jello"
split() "a,b,c".split(",") → ["a", "b", "c"]
join() " ".join(["a","b","c"]) → "a b c"
find() "Python".find("y") → 1
count() "banana".count("a") → 3
startswith() "Python".startswith("Py") → True
endswith() "Python".endswith("on") → True
isdigit() "123".isdigit() → True
5.5 f-Strings (Formatted Strings)
f-strings are the modern, easiest way to include variables inside strings:
name = "Alice"
age = 25
score = 98.5
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
# Use f"..." and {variable} inside
print(f"Name: {name}")
print(f"Age: {age}")
print(f"{name} is {age} years old.")
print(f"Score: {score:.1f}%") # 1 decimal place
# You can do expressions inside {}
print(f"Next year, {name} will be {age + 1} years old.")
Output:
Name: Alice Age: 25 Alice is 25 years old. Score: 98.5% Next year, Alice will be 26 years
old.
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
SECTION 5 — LISTS
Chapter 6: Lists
A list is an ordered, changeable collection of items. Lists are one of the most powerful data structures in
Python. Items can be of any type.
6.1 Creating & Accessing Lists
# Creating a list
fruits = ["apple", "banana", "mango", "orange"]
numbers = [10, 20, 30, 40, 50]
mixed = [1, "hello", 3.14, True] # Mixed types!
# Accessing items by index
print(fruits[0]) # apple
print(fruits[-1]) # orange (last item)
print(fruits[1:3]) # ["banana", "mango"]
# Length of list
print(len(fruits)) # 4
6.2 Modifying Lists
fruits = ["apple", "banana", "mango"]
# Change an item
fruits[1] = "grape"
print(fruits) # ["apple", "grape", "mango"]
# Add item to the end
[Link]("orange")
print(fruits) # ["apple", "grape", "mango", "orange"]
# Insert item at a specific position
[Link](1, "kiwi")
print(fruits) # ["apple", "kiwi", "grape", "mango", "orange"]
# Remove a specific item
[Link]("grape")
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
print(fruits)
# Remove last item
last = [Link]()
print(last, fruits)
# Delete by index
del fruits[0]
print(fruits)
6.3 Common List Methods
Method What it Does
append(x) Add x to the end of the list
insert(i, x) Insert x at position i
remove(x) Remove the first occurrence of x
pop(i) Remove and return item at index i (default: last)
sort() Sort the list in ascending order
reverse() Reverse the order of the list
index(x) Return the index of the first x
count(x) Count how many times x appears
clear() Remove all items from the list
copy() Return a copy of the list
extend(lst) Add all items from another list
numbers = [3, 1, 4, 1, 5, 9, 2, 6]
[Link]()
print(numbers) # [1, 1, 2, 3, 4, 5, 6, 9]
[Link]()
print(numbers) # [9, 6, 5, 4, 3, 2, 1, 1]
print([Link](1)) # 2
print([Link](5)) # 2
6.4 List Comprehension (Intermediate)
List comprehension is a powerful, concise way to create lists:
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
# Traditional way
squares = []
for x in range(1, 6):
[Link](x ** 2)
print(squares) # [1, 4, 9, 16, 25]
# List comprehension way — same result, one line!
squares = [x ** 2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
# With condition — only even numbers
evens = [x for x in range(1, 11) if x % 2 == 0]
print(evens) # [2, 4, 6, 8, 10]
💡 List comprehension: [expression for item in iterable if condition]
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
SECTION 6 — TUPLES, DICTIONARIES & SETS
Chapter 7: Tuples
A tuple is like a list, but it is immutable — it cannot be changed after creation. Use tuples for data that
should not be modified.
# Creating a tuple
coordinates = (10.5, -3.2)
colours = ("red", "green", "blue")
single = (42,) # Single-item tuple needs a trailing comma!
# Accessing items (same as lists)
print(colours[0]) # red
print(colours[-1]) # blue
print(colours[0:2]) # ("red", "green")
# Unpacking a tuple
x, y = coordinates
print(f"x = {x}, y = {y}")
# Trying to change a tuple causes an error!
# colours[0] = 'yellow' # TypeError: 'tuple' object does not support
item assignment
Tuple vs List
Use LISTS when data will change (shopping cart, scores). Use TUPLES when data should
stay fixed (GPS coordinates, RGB colours, days of week).
Chapter 8: Dictionaries
A dictionary stores data in key-value pairs. Each key is unique and is used to access its corresponding
value. Think of it like a real dictionary — look up a word (key) to find its definition (value).
8.1 Creating & Accessing Dictionaries
# Creating a dictionary
student = {
"name": "Alice",
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
"age": 20,
"grade": "A",
"is_enrolled": True
}
# Accessing values
print(student["name"]) # Alice
print([Link]("age")) # 20
print([Link]("score", 0)) # 0 (default if key missing)
# Modify a value
student["age"] = 21
# Add a new key-value pair
student["email"] = "alice@[Link]"
# Delete a key
del student["is_enrolled"]
print(student)
8.2 Dictionary Methods
Method What it Does
keys() Return all keys as a view
values() Return all values as a view
items() Return all key-value pairs as tuples
get(key, default) Return value for key (no error if missing)
update(dict) Update with another dictionary's key-value pairs
pop(key) Remove and return the value for key
clear() Remove all items
in Check if a key exists: 'name' in student → True
student = {"name": "Alice", "age": 20, "grade": "A"}
print([Link]()) # dict_keys(["name", "age", "grade"])
print([Link]()) # dict_values(["Alice", 20, "A"])
# Loop through a dictionary
for key, value in [Link]():
print(f"{key}: {value}")
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
Chapter 9: Sets
A set is an unordered collection of unique items. Duplicates are automatically removed. Sets are useful
for membership testing and removing duplicates.
# Creating a set
fruits = {"apple", "banana", "mango", "apple", "banana"}
print(fruits) # {"apple", "banana", "mango"} — duplicates removed!
# Adding and removing items
[Link]("orange")
[Link]("banana")
# Set operations
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a | b) # Union: {1, 2, 3, 4, 5, 6}
print(a & b) # Intersection: {3, 4}
print(a - b) # Difference: {1, 2}
# Check membership
print("apple" in fruits) # True
# Remove duplicates from a list using a set
numbers = [1, 2, 2, 3, 3, 3, 4]
unique = list(set(numbers))
print(unique) # [1, 2, 3, 4]
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
SECTION 7 — CONTROL FLOW
Chapter 10: if / elif / else Statements
Control flow allows your program to make decisions. The if statement checks a condition and runs code
only if it is True.
10.1 Basic if Statement
# Basic structure
if condition:
# code runs if condition is True
# Example
temperature = 38
if temperature > 37:
print("You have a fever!")
print("Please rest and drink water.")
⚠️not curly
Indentation (4 spaces) is CRITICAL in Python. Python uses indentation to define code blocks,
braces like other languages.
10.2 if / else
score = 65
if score >= 50:
print("You passed! Congratulations!")
else:
print("You did not pass. Try again!")
10.3 if / elif / else
score = 78
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Your grade is: {grade}") # Your grade is: C
10.4 Nested if Statements
age = 20
has_ticket = True
if age >= 18:
if has_ticket:
print("Welcome to the event!")
else:
print("You need a ticket to enter.")
else:
print("Sorry, this event is for adults only.")
# Shorter version using "and"
if age >= 18 and has_ticket:
print("Welcome to the event!")
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
SECTION 8 — LOOPS
Chapter 11: Loops
Loops allow you to repeat a block of code multiple times. Python has two types: for loops and while
loops.
11.1 for Loop
The for loop iterates over a sequence (list, string, range, etc.):
# Loop through a list
fruits = ["apple", "banana", "mango"]
for fruit in fruits:
print(f"I like {fruit}")
# Loop through a string
for letter in "Python":
print(letter)
# Loop using range()
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(1, 6): # 1, 2, 3, 4, 5
print(i)
for i in range(0, 10, 2): # 0, 2, 4, 6, 8 (step of 2)
print(i)
11.2 while Loop
The while loop keeps running as long as a condition is True:
count = 1
while count <= 5:
print(f"Count: {count}")
count += 1 # IMPORTANT: always update the condition!
print("Done!")
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
# Password checker example
password = ""
while password != "secret123":
password = input("Enter password: ")
print("Access granted!")
⚠️infiniteAlways
loop!
make sure your while loop condition eventually becomes False, or you'll create an
11.3 break, continue, pass
# break — exit the loop immediately
for i in range(10):
if i == 5:
break
print(i)
# Prints: 0 1 2 3 4
# continue — skip the rest of this iteration
for i in range(10):
if i % 2 == 0:
continue
print(i)
# Prints: 1 3 5 7 9
# pass — do nothing (placeholder)
for i in range(5):
pass # Loop runs but does nothing
11.4 enumerate() and zip() (Intermediate)
# enumerate() — get index AND value together
fruits = ["apple", "banana", "mango"]
for index, fruit in enumerate(fruits):
print(f"{index + 1}. {fruit}")
# Output:
# 1. apple
# 2. banana
# 3. mango
# zip() — loop through two lists at once
names = ["Alice", "Bob", "Carol"]
scores = [85, 92, 78]
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
for name, score in zip(names, scores):
print(f"{name}: {score}")
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
SECTION 9 — FUNCTIONS
Chapter 12: Functions
A function is a reusable block of code that performs a specific task. Functions help you organise your
code, avoid repetition, and make programs easier to understand.
12.1 Defining and Calling Functions
# Define a function using "def"
def greet():
print("Hello! Welcome to Python.")
print("Hope you are enjoying the course!")
# Call the function (run it)
greet()
greet() # Can call multiple times!
12.2 Functions with Parameters
# Function with parameters (inputs)
def greet_person(name):
print(f"Hello, {name}! Welcome!")
greet_person("Alice")
greet_person("Bob")
# Multiple parameters
def add(a, b):
result = a + b
print(f"{a} + {b} = {result}")
add(5, 3)
add(10, 25)
12.3 Return Values
# Functions can return a value using "return"
def square(number):
return number ** 2
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
result = square(5)
print(result) # 25
print(square(10)) # 100
# Return multiple values
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([3, 1, 8, 5, 2])
print(f"Min: {low}, Max: {high}") # Min: 1, Max: 8
12.4 Default & Keyword Arguments
# Default argument — used if no value is provided
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob", "Good morning") # Good morning, Bob!
# Keyword arguments — specify by name (order does not matter)
def describe_pet(animal, name):
print(f"I have a {animal} named {name}.")
describe_pet(name="Buddy", animal="dog")
12.5 Scope — Where Variables Live
# Local scope — variable exists only inside the function
def my_function():
local_var = "I am local"
print(local_var) # Works fine inside
my_function()
# print(local_var) # ERROR! local_var does not exist here
# Global scope — variable exists everywhere
global_var = "I am global"
def show():
print(global_var) # Can read global variable
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
show()
12.6 Lambda Functions (Intermediate)
Lambda functions are small anonymous (unnamed) functions defined in one line:
# Regular function
def double(x):
return x * 2
# Lambda equivalent
double = lambda x: x * 2
print(double(5)) # 10
# Lambda with multiple arguments
add = lambda a, b: a + b
print(add(3, 7)) # 10
# Useful with sorted()
students = [("Alice", 85), ("Bob", 92), ("Carol", 78)]
sorted_students = sorted(students, key=lambda s: s[1], reverse=True)
print(sorted_students)
# [("Bob", 92), ("Alice", 85), ("Carol", 78)]
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
SECTION 10 — MODULES & LIBRARIES
Chapter 13: Modules and Libraries
A module is a Python file containing functions, classes, and variables that you can import and use in
your program. Python comes with hundreds of built-in modules, and thousands more can be installed.
13.1 Importing Modules
# Import the whole module
import math
print([Link]) # 3.141592653589793
print([Link](16)) # 4.0
print([Link](4.3)) # 5
print([Link](4.7)) # 4
# Import specific functions only
from math import sqrt, pi
print(sqrt(25)) # 5.0
print(pi) # 3.141592653589793
# Import with an alias (nickname)
import math as m
print([Link](9)) # 3.0
13.2 Essential Built-in Modules
Module Purpose & Key Functions
math Mathematical functions: sqrt, ceil, floor, pow, log,
sin, cos, pi
random Generate random numbers: random(), randint(),
choice(), shuffle()
datetime Work with dates and times: [Link](),
[Link]()
os Interact with the operating system: getcwd(),
listdir(), mkdir()
sys System-specific parameters: [Link], [Link](),
[Link]
string String constants and utilities: ascii_letters,
digits
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
re Regular expressions for advanced text searching
json Read and write JSON data: [Link](), [Link]()
time Time-related functions: time(), sleep()
collections Specialised data structures: Counter, defaultdict,
deque
13.3 The random Module
import random
# Random float between 0 and 1
print([Link]())
# Random integer between a and b (inclusive)
print([Link](1, 10))
# Random choice from a list
fruits = ["apple", "banana", "mango", "orange"]
print([Link](fruits))
# Shuffle a list in-place
numbers = [1, 2, 3, 4, 5]
[Link](numbers)
print(numbers)
# Random sample (no repeats)
sample = [Link](range(1, 50), 6)
print(sample) # Like a lottery!
13.4 The datetime Module
from datetime import datetime, date
# Current date and time
now = [Link]()
print(now) # 2025-01-15 14:30:45.123456
print([Link])
print([Link])
print([Link])
print([Link])
# Format date as string
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
print([Link]("%d/%m/%Y")) # 15/01/2025
print([Link]("%B %d, %Y")) # January 15, 2025
# Today's date only
today = [Link]()
print(today)
13.5 Popular Third-Party Libraries
These must be installed using pip (pip install library_name):
Library What It's Used For
numpy Fast numerical computing, arrays, and matrices
pandas Data analysis and manipulation (DataFrames)
matplotlib Create charts, graphs, and plots
seaborn Beautiful statistical visualisations
requests Make HTTP requests (talk to web APIs)
flask Build lightweight web applications
django Full-featured web framework
scikit-learn Machine learning algorithms
tensorflow Deep learning and neural networks
pillow (PIL) Image processing and manipulation
beautifulsoup4 Web scraping — extract data from HTML
pygame Build 2D games
sqlalchemy Work with databases using Python objects
openpyxl Read and write Excel files
Installing Libraries
Use pip in your terminal/command prompt: pip install numpy pip install pandas matplotlib
pip install requests flask To install multiple at once: pip install numpy pandas matplotlib
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
SECTION 11 — USER INPUT & ERROR HANDLING
Chapter 14: User Input
# input() always returns a string!
name = input("What is your name? ")
print(f"Hello, {name}!")
# Convert to the right type
age = int(input("How old are you? "))
print(f"In 10 years, you will be {age + 10}")
# Float input
price = float(input("Enter price: "))
print(f"With 10% tax: {price * 1.10:.2f}")
Chapter 15: Error Handling (try / except)
Errors (exceptions) happen. Good programs handle them gracefully instead of crashing.
# Basic try/except
try:
number = int(input("Enter a number: "))
print(f"10 divided by {number} = {10 / number}")
except ValueError:
print("That was not a valid number!")
except ZeroDivisionError:
print("Cannot divide by zero!")
except Exception as e:
print(f"An unexpected error occurred: {e}")
else:
print("No errors! Great job.")
finally:
print("This always runs, error or not.")
Exception When it Occurs
ValueError Wrong value type (e.g., int('hello'))
TypeError Wrong data type used in operation
ZeroDivisionError Dividing by zero
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
IndexError List index out of range
KeyError Dictionary key not found
FileNotFoundError File does not exist
NameError Variable not defined
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
SECTION 12 — FILE HANDLING
Chapter 16: Working with Files
# Writing to a file
with open("[Link]", "w") as file:
[Link]("Hello from Python!\n")
[Link]("This is line 2.\n")
# Reading from a file
with open("[Link]", "r") as file:
content = [Link]()
print(content)
# Read line by line
with open("[Link]", "r") as file:
for line in file:
print([Link]())
# Append to a file (does not overwrite)
with open("[Link]", "a") as file:
[Link]("This is a new line.\n")
Mode Meaning
"r" Read (default). File must exist.
"w" Write. Creates new file or OVERWRITES existing.
"a" Append. Adds to end of file. Creates if not exists.
"r+" Read and write.
"rb" / "wb" Read/write binary files (images, etc.)
💡 Always use "with open()" — it automatically closes the file even if an error occurs.
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
QUICK REFERENCE CHEAT SHEET
Python Cheat Sheet
Built-in Functions
Function What it Does
print(x) Display output to screen
input(prompt) Get text input from user
len(x) Return length of string, list, etc.
type(x) Return the data type of x
int(x) Convert x to integer
float(x) Convert x to float
str(x) Convert x to string
bool(x) Convert x to boolean
list(x) Convert x to list
range(a, b, step) Generate a sequence of numbers
abs(x) Absolute value
round(x, n) Round x to n decimal places
min(x) Return minimum value
max(x) Return maximum value
sum(x) Sum of all items in a list
sorted(x) Return sorted version of x
reversed(x) Return reversed version of x
enumerate(x) Return (index, value) pairs
zip(a, b) Combine two sequences together
map(fn, x) Apply function to every item
filter(fn, x) Filter items by function
open(file, mode) Open a file
help(x) Show documentation for x
dir(x) List all attributes and methods of x
Common Keyboard Shortcuts (Python IDLE / VS Code)
Shortcut Action
Python Teaching Notes | Page
🐍 Python Programming — Complete Teaching Notes Basic & Intermediate
F5 (IDLE) / Ctrl+F5 (VS Code) Run program
Ctrl + Z Undo
Ctrl + S Save
Ctrl + / Comment/uncomment selected lines
Tab Indent (add 4 spaces)
Shift + Tab De-indent (remove 4 spaces)
Ctrl + C (terminal) Stop/kill running program
Golden Rules of Python Programming
1. Indentation matters — always use 4 spaces per level. 2. Read error messages carefully
— they tell you exactly what went wrong. 3. Comment your code — your future self will
thank you. 4. Test small pieces of code before combining them. 5. Practice every day —
even 15 minutes a day makes a huge difference! 6. When stuck, break the problem into
smaller steps. 7. Use print() to check what your variables contain at any point.
Next Steps — Keep Learning!
After mastering these basics, explore: • Object-Oriented Programming (Classes & Objects) •
Working with APIs and JSON data • NumPy and Pandas for data analysis • Flask or Django
for web development • Tkinter for desktop GUI apps • Pygame for building games • Practice
on: [Link]/python, [Link], [Link]
Python Teaching Notes | Page