A hands-on, 10-module course that takes you from zero to building real Python programs. Each module has short lessons, code to try, exercises, and a mini project. Plan on 30 to 60 minutes per module.
How to Use This Course
- Type every example yourself. Don’t copy and paste.
- Do the exercises before looking at hints.
- Errors are normal. Read the message, it usually tells you what’s wrong.
- Build the mini project at the end of each module.
Setup: Install Python from python.org (version 3.12 or newer). Use VS Code, or try code online at replit.com or python.org/shell. Check it works by running python --version in a terminal.
Module 1: Your First Program
Goal: Run code and print output.
print("Hello, world!")print("I am learning Python")
Key ideas
print()shows text on screen.- Text goes inside quotes (a string).
- Lines starting with
#are comments. Python ignores them. - Python runs code top to bottom, one line at a time.
# This is a commentprint("Python is fun") # comment after code
Exercises
- Print your name.
- Print three lines about your favorite hobby.
- Add a comment above each line.
Mini project: Print a small “business card” with your name, city and favorite food.
Module 2: Variables and Data Types
Goal: Store and use information.
A variable is a labeled box that holds a value.
name = "Sam" age = 25 height = 1.75 is_student = Trueprint(name, age, height, is_student)
The four basic types
| Type | Name | Example |
|---|---|---|
str | text | "hello" |
int | whole number | 42 |
float | decimal | 3.14 |
bool | True or False | True |
Check a type with type(x):
print(type(42)) # <class 'int'>print(type("hi")) # <class 'str'>
Naming rules
- Use letters, numbers and underscores. Can’t start with a number.
- Use
snake_case:first_name, notFirstName. - Names are case sensitive:
ageandAgeare different.
f-strings put variables inside text:
name = "Sam"age = 25print(f"{name} is {age} years old")
Getting input
name = input("What is your name? ")print(f"Nice to meet you, {name}!")
input() always returns a string. Convert it when you need a number:
age = int(input("Age? "))print(f"Next year you will be {age + 1}")
Exercises
- Store your favorite number in a variable and print it.
- Ask for a name and greet the person.
- Ask for two numbers and print their sum.
Mini project: A “Mad Libs” game. Ask for a noun, a verb and an adjective, then print a silly sentence using them.
Module 3: Operators and Strings
Goal: Do math and work with text.
Math operators
print(7 + 3) # 10 additionprint(7 - 3) # 4 subtractionprint(7 * 3) # 21 multiplicationprint(7 / 2) # 3.5 division (always a float)print(7 // 2) # 3 floor divisionprint(7 % 2) # 1 remainderprint(2 ** 3) # 8 power
Python follows normal math order. Use parentheses to be clear: (2 + 3) * 4.
Shortcuts
score = 10score += 5 # same as score = score + 5score -= 2score *= 2
Comparison operators give True or False:
print(5 == 5) # equalprint(5 != 3) # not equalprint(5 > 3, 5 < 3, 5 >= 5, 5 <= 4)
Logical operators: and, or, not
age = 20print(age > 18 and age < 65) # Trueprint(not age > 18) # False
String tools
word = "Python"print(len(word)) # 6print(word.upper()) # PYTHONprint(word.lower()) # pythonprint(word[0]) # P (first character)print(word[-1]) # n (last character)print(word[0:3]) # Pyt (slice)print("Py" in word) # Trueprint(" hi ".strip()) # hiprint("a,b,c".split(",")) # ['a', 'b', 'c']print(word.replace("P", "J")) # Jython
Indexing starts at 0, not 1.
Exercises
- Convert 100 minutes into hours and minutes using
//and%. - Ask for a word and print it in uppercase with its length.
- Check whether a number is even using
%.
Mini project: A tip calculator. Ask for a bill total and tip percent, then print the tip and the total.
Module 4: Making Decisions (Conditionals)
Goal: Make your program choose.
age = int(input("Age? "))if age >= 18:
print("Adult")
elif age >= 13:
print("Teenager")
else:
print("Child")
Rules
- End the
ifline with a colon:. - Indent the code inside by 4 spaces. Indentation is how Python knows what belongs together.
elifmeans “else if”. You can have many.elseis optional.
Combining conditions
has_ticket = True is_open = Trueif has_ticket and is_open:
print("Come in")
Truthiness: empty values count as False.
name = ""if not name: print("Name is empty")
Exercises
- Print whether a number is positive, negative or zero.
- Grade converter: 90+ is A, 80+ is B, 70+ is C, otherwise F.
- Leap year checker (divisible by 4, except centuries unless divisible by 400).
Mini project: A number guessing check. Store a secret number, ask for a guess, and print “too high”, “too low” or “correct”.
Module 5: Loops
Goal: Repeat actions without copying code.
for loop: repeat a set number of times
for i in range(5): print(i) # 0 1 2 3 4for i in range(1, 6):
print(i) # 1 2 3 4 5for i in range(0, 10, 2):
print(i) # 0 2 4 6 8
Loop over text or lists
for letter in "cat": print(letter)for fruit in ["apple", "banana", "cherry"]:
print(fruit)
while loop: repeat while something is true
count = 3while count > 0: print(count) count -= 1print("Liftoff!")
If the condition never becomes False you get an infinite loop. Press Ctrl+C to stop it.
Control keywords
for n in range(10): if n == 3: continue # skip this round if n == 6: break # stop the loop print(n)
Pattern: keep asking until valid
while True: answer = input("Type yes to continue: ") if answer == "yes": break
Pattern: running total
total = 0for n in range(1, 11): total += nprint(total) # 55
Exercises
- Print the multiplication table for any number.
- Sum all even numbers from 1 to 100.
- Print a right triangle of stars (
*,**,***…). - FizzBuzz: for 1 to 30 print Fizz for multiples of 3, Buzz for 5, FizzBuzz for both, otherwise the number.
Mini project: A complete number guessing game. The computer picks a random number and the player keeps guessing until correct.
import randomsecret = random.randint(1, 20)
Module 6: Lists, Tuples, Sets and Dictionaries
Goal: Store collections of data.
Lists are ordered and changeable.
colors = ["red", "green", "blue"]print(colors[0]) # red
colors.append("yellow") # add to end
colors.insert(1, "pink") # add at position
colors.remove("green") # remove by value
last = colors.pop() # remove and return last
print(len(colors))
colors.sort() # sort in placenumbers = [4, 8, 1]
print(sum(numbers), max(numbers), min(numbers))
Tuples are ordered but can’t be changed.
point = (3, 5)x, y = point # unpacking
Sets hold unique values with no order.
nums = {1, 2, 2, 3, 3}print(nums) # {1, 2, 3}
Dictionaries store key and value pairs.
person = {"name": "Sam", "age": 25}print(person["name"])
person["city"] = "Lagos" # add
person["age"] = 26 # update
print(person.get("job", "none")) # safe lookup with defaultfor key, value in person.items():
print(key, value)
List comprehensions build lists in one line:
squares = [n * n for n in range(1, 6)] # [1, 4, 9, 16, 25]evens = [n for n in range(10) if n % 2 == 0]
Choosing the right one
| Need | Use |
|---|---|
| Ordered items you will change | list |
| Fixed group of values | tuple |
| Unique items, fast “is it in here?” | set |
| Look things up by name | dict |
Exercises
- Make a list of 5 numbers and print the largest and the average.
- Remove duplicates from a list using a set.
- Count how many times each letter appears in a word using a dictionary.
Mini project: A to-do list app. Show a menu to add a task, view tasks, and remove a task, running in a loop until the user quits.
Module 7: Functions
Goal: Package code so you can reuse it.
def greet(name): print(f"Hello, {name}!")greet("Sam")
greet("Ada")
Return values
def add(a, b): return a + bresult = add(3, 4)
print(result) # 7
print shows something. return hands a value back so you can use it.
Default and keyword arguments
def power(base, exponent=2): return base ** exponentprint(power(5)) # 25
print(power(2, 3)) # 8
print(power(exponent=3, base=2))
Scope: variables made inside a function exist only inside it.
def test(): x = 10 # local variabletest()print(x) # would cause an error
Docstrings describe what a function does:
def area(width, height): """Return the area of a rectangle.""" return width * height
Good function habits
- One function, one job.
- Use clear verb names:
calculate_total,is_even. - Prefer returning values over printing inside.
Exercises
- Write
is_even(n)that returns True or False. - Write
average(numbers)that takes a list. - Write
is_palindrome(word).
Mini project: Rebuild your tip calculator and guessing game using functions. Add a main() function that runs the program.
def main(): print("Program starts here")if name == "main":
main()
Module 8: Files, Errors and Modules
Goal: Save data, handle problems, and use other people’s code.
Reading and writing files
with open("notes.txt", "w") as f: f.write("First line\n") f.write("Second line\n")with open("notes.txt", "r") as f:
content = f.read()
print(content)with open("notes.txt") as f:
for line in f:
print(line.strip())
Modes: "r" read, "w" write (erases old content), "a" append. The with block closes the file for you.
Handling errors
try: number = int(input("Enter a number: ")) print(10 / number)except ValueError: print("That wasn't a number")except ZeroDivisionError: print("Can't divide by zero")
Common errors you will meet:
| Error | Usual cause |
|---|---|
SyntaxError | typo, missing colon or bracket |
NameError | variable not defined or misspelled |
TypeError | mixing types, like "5" + 5 |
IndexError | list position doesn’t exist |
KeyError | dictionary key doesn’t exist |
IndentationError | wrong spacing |
Modules
import math print(math.sqrt(16), math.pi)import random
print(random.choice(["a", "b", "c"]))from datetime import datetime
print(datetime.now())
Installing packages with pip:
pip install requests
JSON is a common format for saving structured data:
import jsondata = {"name": "Sam", "scores": [90, 85]} with open("data.json", "w") as f:
json.dump(data, f)with open("data.json") as f:
loaded = json.load(f)
Exercises
- Write a program that saves a list of names to a file and reads them back.
- Make
input()for a number keep asking until the user types a valid one. - Count the words in a text file.
Mini project: Upgrade your to-do app so tasks are saved to a JSON file and still there next time you run it.
Module 9: Object-Oriented Programming Basics
Goal: Model real things with classes.
A class is a blueprint. An object is something built from it.
class Dog: def __init__(self, name, age): self.name = name self.age = agedef bark(self): print(f"{self.name} says woof!") def birthday(self): self.age += 1rex = Dog("Rex", 3)
rex.bark()
rex.birthday()
print(rex.age) # 4
Key terms
__init__runs when you create an object.selfmeans “this particular object”.- Variables on an object are attributes. Functions inside a class are methods.
Inheritance lets a class reuse another:
class Animal: def __init__(self, name): self.name = namedef speak(self): print("...")class Cat(Animal):
def speak(self):
print(f"{self.name} says meow")Cat("Mia").speak()
Example: a bank account
class BankAccount: def __init__(self, owner, balance=0): self.owner = owner self.balance = balance def deposit(self, amount): self.balance += amount def withdraw(self, amount): if amount > self.balance: print("Not enough money") else: self.balance -= amount
Exercises
- Create a
Rectangleclass witharea()andperimeter()methods. - Create a
Studentclass that stores grades and returns the average. - Make
Carinherit from aVehicleclass.
Mini project: A simple inventory system with an Item class and a Store class that holds many items.
Module 10: Final Projects and Next Steps
Goal: Combine everything and keep growing.
Choose one capstone project
- Quiz game: questions stored in a dictionary, score tracking, saved high scores in a file.
- Expense tracker: add expenses with categories, show totals per category, save to JSON.
- Text adventure: rooms, choices, an inventory, and win or lose endings.
- Password generator: random passwords with length and character options.
- Contact book: add, search, edit and delete contacts using classes and files.
Capstone checklist
- Plan first: write what the program should do in plain sentences.
- Break it into small functions.
- Handle bad input with
tryandexcept. - Save and load data from a file.
- Test after every small change.
- Add comments and docstrings.
Debugging toolkit
- Read the error message from the bottom up. The last line names the problem.
- Add
print()statements to see what values really are. - Test small pieces separately.
- Explain the code line by line out loud.
- Search the exact error message online.
Style tips
- Follow PEP 8: 4-space indents,
snake_casenames, lines under about 79 characters. - Choose names that explain themselves.
- Don’t repeat yourself. If you copy code twice, make a function.
Where to Go Next
Pick a direction based on what excites you:
| Interest | Learn next |
|---|---|
| Data and analysis | pandas, matplotlib, Jupyter notebooks |
| Websites | Flask or Django |
| Automation | os, pathlib, requests, selenium |
| Games | pygame |
| AI and machine learning | NumPy, scikit-learn |
| Better coding | Git and GitHub, testing with pytest, virtual environments |
Suggested 8-Week Schedule
| Week | Modules | Focus |
|---|---|---|
| 1 | 1, 2 | Setup, printing, variables |
| 2 | 3, 4 | Operators, strings, if statements |
| 3 | 5 | Loops |
| 4 | 6 | Collections |
| 5 | 7 | Functions |
| 6 | 8 | Files, errors, modules |
| 7 | 9 | Classes |
| 8 | 10 | Capstone project |
Practice Tips That Make It Stick
- Code a little every day. 30 minutes daily beats 4 hours once a week.
- Retype a finished exercise from memory a few days later.
- Change working examples to see what breaks.
- Build things you actually care about.
- Share your projects and read other people’s code.
You’re ready to start. Open Module 1 and write your first line of code.





Leave a Reply