Absolute beginner? Perfect. Python is the best first language โ it reads almost like plain English. Open a terminal and type
python3 to get an interactive shell. Type every example as you go.Chapter 1 โ What is Python?
Python is a high-level, general-purpose programming language created by Guido van Rossum in 1991. It's used for web development, data science, AI, automation, scripting, and cybersecurity.
Why Python first? Clean syntax, massive community, runs everywhere, and you can build real things in minutes.
# Install Python (check if already installed):
python3 --version
# Python 3.11.4
# Open interactive shell:
python3
>>>
# Run a script:
python3 myfile.py
# Install packages:
pip3 install requests
Chapter 2 โ Your First Program
# The traditional first program
print("Hello, World!")
# Output: Hello, World!
# print() displays text on screen
# Text inside quotes is called a STRING
print("My name is Uzair")
print("I am learning Python")
print(42)
print(3.14)
# Ask the user for input:
name = input("What is your name? ")
print("Hello, " + name + "!")
# Comments โ lines Python ignores (use for notes)
# This is a comment
# Python skips it when running
Chapter 3 โ Variables & Data Types
# Variables store data โ no type declaration needed in Python
name = "Alice" # str (string โ text)
age = 25 # int (integer โ whole number)
height = 1.75 # float (decimal number)
is_student = True # bool (True or False)
# Check the type of a variable:
print(type(name)) # <class 'str'>
print(type(age)) # <class 'int'>
print(type(height)) # <class 'float'>
print(type(is_student)) # <class 'bool'>
# Convert between types:
x = "42" # string "42"
y = int(x) # integer 42
z = float(x) # float 42.0
s = str(100) # string "100"
# Multiple assignment:
a, b, c = 1, 2, 3
x = y = z = 0 # all equal 0
# Naming rules:
# - Start with letter or underscore
# - No spaces (use_underscores)
# - Case sensitive: Name โ name
Chapter 4 โ Operators
# Arithmetic operators:
print(10 + 3) # 13 (addition)
print(10 - 3) # 7 (subtraction)
print(10 * 3) # 30 (multiplication)
print(10 / 3) # 3.333... (division โ always float)
print(10 // 3) # 3 (floor division โ drops decimal)
print(10 % 3) # 1 (modulus โ remainder)
print(2 ** 8) # 256 (power)
# Comparison operators (return True or False):
print(5 == 5) # True (equal)
print(5 != 3) # True (not equal)
print(5 > 3) # True (greater than)
print(5 < 3) # False (less than)
print(5 >= 5) # True (greater or equal)
# Logical operators:
print(True and False) # False (both must be True)
print(True or False) # True (at least one True)
print(not True) # False (reverse)
# Shorthand assignment:
x = 10
x += 5 # x = x + 5 โ 15
x -= 3 # x = x - 3 โ 12
x *= 2 # x = x * 2 โ 24
Chapter 5 โ Strings
# Strings = text, wrapped in single or double quotes
greeting = "Hello, World!"
name = 'Alice'
# String length:
print(len(greeting)) # 13
# Access characters by index (starts at 0):
print(greeting[0]) # H
print(greeting[-1]) # ! (last character)
# Slice (get a portion):
print(greeting[0:5]) # Hello
print(greeting[7:]) # World!
print(greeting[:5]) # Hello
# String methods:
text = " hello world "
print(text.upper()) # " HELLO WORLD "
print(text.lower()) # " hello world "
print(text.strip()) # "hello world" (remove spaces)
print(text.replace("hello", "hi")) # " hi world "
print("hello world".split(" ")) # ['hello', 'world']
print(",".join(["a", "b", "c"])) # "a,b,c"
print("hello".startswith("hel")) # True
print("world" in "hello world") # True
# f-strings (best way to format strings):
name = "Uzair"
age = 25
print(f"My name is {name} and I am {age} years old.")
print(f"2 + 2 = {2 + 2}") # expressions work inside {}
Chapter 6 โ Lists & Tuples
# Lists = ordered, changeable collections [ ]
fruits = ["apple", "banana", "cherry"]
numbers = [1, 2, 3, 4, 5]
mixed = [1, "hello", True, 3.14]
# Access items (index starts at 0):
print(fruits[0]) # apple
print(fruits[-1]) # cherry (last item)
print(fruits[0:2]) # ['apple', 'banana']
# Modify lists:
fruits.append("mango") # add to end
fruits.insert(1, "orange") # insert at index 1
fruits.remove("banana") # remove by value
fruits.pop() # remove last item
fruits.pop(0) # remove at index 0
fruits.sort() # sort alphabetically
fruits.reverse() # reverse order
print(len(fruits)) # number of items
# List comprehension (create list with one line):
squares = [x**2 for x in range(1, 6)]
# [1, 4, 9, 16, 25]
evens = [x for x in range(20) if x % 2 == 0]
# [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Tuples = ordered, UNCHANGEABLE collections ( )
point = (3, 7)
rgb = (255, 128, 0)
print(point[0]) # 3
# point[0] = 5 โ ERROR! Tuples can't be changed
x, y = point # unpack: x=3, y=7
Chapter 7 โ Dictionaries & Sets
# Dictionary = key โ value pairs { }
person = {
"name": "Uzair",
"age": 25,
"city": "Lahore"
}
# Access values by key:
print(person["name"]) # Uzair
print(person.get("age")) # 25
print(person.get("email", "N/A")) # N/A (default if missing)
# Add / update / delete:
person["email"] = "uzair@example.com" # add
person["age"] = 26 # update
del person["city"] # delete
# Iterate a dictionary:
for key in person:
print(f"{key}: {person[key]}")
for key, value in person.items():
print(f"{key} = {value}")
# All keys / values:
print(person.keys()) # dict_keys(['name', 'age', 'email'])
print(person.values()) # dict_values(['Uzair', 26, 'uzair@...'])
print("name" in person) # True
# Sets = unordered, unique values { }
colours = {"red", "green", "blue", "red"}
print(colours) # {'red', 'green', 'blue'} โ duplicate removed!
colours.add("yellow")
colours.discard("green")
print(len(colours))
# Set operations:
a = {1, 2, 3, 4}
b = {3, 4, 5, 6}
print(a & b) # {3, 4} (intersection)
print(a | b) # {1,2,3,4,5,6} (union)
print(a - b) # {1, 2} (difference)
Chapter 8 โ If / Elif / Else
# Make decisions based on conditions
age = 18
if age >= 18:
print("You are an adult")
elif age >= 13:
print("You are a teenager")
else:
print("You are a child")
# Indentation matters! Python uses spaces, not braces { }
# Multiple conditions:
username = "admin"
password = "secret"
if username == "admin" and password == "secret":
print("Login successful!")
else:
print("Wrong credentials.")
# Ternary (one-line if/else):
status = "adult" if age >= 18 else "minor"
print(status) # adult
# Nested if:
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "F"
print(f"Grade: {grade}") # Grade: B
Chapter 9 โ Loops
# for loop โ iterate over a sequence
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for i in range(1, 6):
print(i) # 1, 2, 3, 4, 5
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
# Iterate over a list:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Enumerate (get index AND value):
for i, fruit in enumerate(fruits):
print(f"{i}: {fruit}") # 0: apple, 1: banana, 2: cherry
# while loop โ repeat while condition is True
count = 0
while count < 5:
print(count)
count += 1 # ALWAYS increment or you get infinite loop!
# break โ exit loop early
for i in range(10):
if i == 5:
break # stops at 5
print(i)
# continue โ skip this iteration, go to next
for i in range(10):
if i % 2 == 0:
continue # skip even numbers
print(i) # prints only odd: 1,3,5,7,9
Chapter 10 โ Functions
# Functions = reusable blocks of code
def greet():
print("Hello!")
greet() # call the function โ Hello!
# Functions with parameters:
def greet(name):
print(f"Hello, {name}!")
greet("Uzair") # Hello, Uzair!
# Default parameters:
def greet(name, greeting="Hello"):
print(f"{greeting}, {name}!")
greet("Alice") # Hello, Alice!
greet("Bob", "Good morning") # Good morning, Bob!
# Return values:
def add(a, b):
return a + b
result = add(3, 7)
print(result) # 10
# Return multiple values:
def min_max(numbers):
return min(numbers), max(numbers)
low, high = min_max([5, 2, 8, 1, 9])
print(low, high) # 1 9
# *args โ accept any number of arguments:
def total(*numbers):
return sum(numbers)
print(total(1, 2, 3, 4, 5)) # 15
# **kwargs โ accept named arguments:
def profile(**info):
for key, value in info.items():
print(f"{key}: {value}")
profile(name="Uzair", age=25, city="Lahore")
# Lambda (anonymous one-line function):
square = lambda x: x ** 2
print(square(5)) # 25
double = lambda x: x * 2
nums = [1, 2, 3, 4]
print(list(map(double, nums))) # [2, 4, 6, 8]
Chapter 11 โ Modules & pip
# Import built-in modules:
import math
print(math.pi) # 3.141592653589793
print(math.sqrt(16)) # 4.0
print(math.ceil(4.2)) # 5
print(math.floor(4.9)) # 4
import random
print(random.randint(1, 10)) # random number 1-10
print(random.choice(["a","b","c"])) # random item
random.shuffle([1,2,3,4,5]) # shuffle a list
import datetime
now = datetime.datetime.now()
print(now) # 2025-06-15 14:32:10.123456
print(now.year, now.month) # 2025 6
import os
print(os.getcwd()) # current directory
print(os.listdir(".")) # files in current dir
import sys
print(sys.argv) # command-line arguments
# Install third-party packages with pip:
# pip3 install requests
# pip3 install numpy pandas
# pip3 install flask (web framework)
# pip3 install pillow (image processing)
# Create your own module (save as utils.py):
def add(a, b):
return a + b
PI = 3.14159
# Import your module:
import utils
print(utils.add(2, 3)) # 5
print(utils.PI) # 3.14159
Chapter 12 โ File I/O
# Write to a file:
with open("hello.txt", "w") as f:
f.write("Hello, World!\n")
f.write("Second line\n")
# "w" = write (creates/overwrites)
# "a" = append (adds to end)
# "r" = read (default)
# Read entire file:
with open("hello.txt", "r") as f:
content = f.read()
print(content)
# Read line by line:
with open("hello.txt", "r") as f:
for line in f:
print(line.strip())
# Read all lines into a list:
with open("hello.txt", "r") as f:
lines = f.readlines()
print(lines) # ['Hello, World!\n', 'Second line\n']
# Check if file exists:
import os
if os.path.exists("hello.txt"):
print("File exists!")
# Work with CSV files:
import csv
with open("data.csv", "w", newline="") as f:
writer = csv.writer(f)
writer.writerow(["Name", "Age", "City"])
writer.writerow(["Alice", 25, "London"])
writer.writerow(["Bob", 30, "Paris"])
with open("data.csv", "r") as f:
reader = csv.reader(f)
for row in reader:
print(row)
Chapter 13 โ Error Handling
# try/except โ catch errors instead of crashing
try:
result = 10 / 0
except ZeroDivisionError:
print("Can't divide by zero!")
# Catch multiple exceptions:
try:
number = int(input("Enter a number: "))
result = 100 / number
print(f"Result: {result}")
except ValueError:
print("That's not a number!")
except ZeroDivisionError:
print("Can't divide by zero!")
# else โ runs if no error occurred:
try:
x = int("42")
except ValueError:
print("Error!")
else:
print(f"Success! x = {x}")
# finally โ always runs (cleanup):
try:
f = open("data.txt", "r")
content = f.read()
except FileNotFoundError:
print("File not found!")
finally:
print("Done attempting to read file.")
# Common exception types:
ValueError โ wrong value type (int("hello"))
TypeError โ wrong type operation (1 + "a")
IndexError โ list index out of range
KeyError โ dict key doesn't exist
FileNotFoundError โ file doesn't exist
ZeroDivisionError โ dividing by zero
AttributeError โ object has no attribute
# Raise your own exceptions:
def set_age(age):
if age < 0:
raise ValueError(f"Age can't be negative: {age}")
return age
Chapter 14 โ Mini Projects
# PROJECT 1: Number Guessing Game
import random
def guessing_game():
secret = random.randint(1, 100)
attempts = 0
print("I'm thinking of a number between 1 and 100!")
while True:
guess = int(input("Your guess: "))
attempts += 1
if guess < secret:
print("Too low! Try higher.")
elif guess > secret:
print("Too high! Try lower.")
else:
print(f"Correct! You got it in {attempts} attempts!")
break
guessing_game()
# PROJECT 2: Simple Calculator
def calculator():
print("Simple Calculator")
a = float(input("First number: "))
op = input("Operator (+, -, *, /): ")
b = float(input("Second number: "))
if op == "+": print(a + b)
elif op == "-": print(a - b)
elif op == "*": print(a * b)
elif op == "/":
if b == 0: print("Can't divide by zero!")
else: print(a / b)
else: print("Unknown operator")
calculator()
# PROJECT 3: To-Do List
todos = []
while True:
action = input("add/view/remove/quit: ").lower()
if action == "add":
task = input("Task: ")
todos.append(task)
print(f"Added: {task}")
elif action == "view":
if not todos: print("No tasks!")
for i, task in enumerate(todos, 1):
print(f"{i}. {task}")
elif action == "remove":
num = int(input("Task number to remove: ")) - 1
if 0 <= num < len(todos):
print(f"Removed: {todos.pop(num)}")
elif action == "quit":
break
Workbook Complete! You now know Python fundamentals. Keep practising by building your own projects. Next step: web development with Flask, data analysis with pandas, or security scripting.