Python Workbook — Class 8 (Friendly + Definitions +
Examples)
Week 1 — Introduction to Python
Definition — What is Programming?
Programming is the process of writing step-by-step instructions so a computer can perform tasks.
These instructions must be clear and complete because a computer only follows exactly what you
say. Programming helps us automate work, build games, create websites, and solve problems.
Definition — Why Python?
Python is a high-level, user-friendly programming language. It is simple to read and write, making it
perfect for beginners. Python is powerful and used in web development, data science, AI, and many
real-world projects.
Long Example — A friendly introduction
Think of programming like making a sandwich. You give steps: take bread, add butter, add filling,
close the sandwich. If you forget to add butter, the sandwich might be dry. Similarly, if a program
misses a step, it will not work as expected.
Now a small Python conversation example:
name = input("What is your name? ")
print("Hello, "+ name + "! Welcome to Python.")
Explanation (step-by-step):
1) The computer shows the message inside input() and waits for the user to type.
2) The typed text becomes the value of variable name.
3) print() then shows a greeting using that value.
Classwork
1. Print: Welcome to Python!
2. Print your name and your school's name.
3. Ask the user for their favorite snack and print: "I like too!"
Homework
1. Ask the user where they live and print: " is a nice place!"
2. Create a three-line poem and print each line on a new line.
Week 2 — Variables & Data Types
Definition — Variables
Variables are named containers that hold information. You can store numbers, text, and more inside
variables, and change them whenever you want. They help us give names to values so programs are
easier to read and use.
Definition — Common Data Types
- int: whole numbers (e.g., 10, -3).
- float: decimal numbers (e.g., 3.14).
- str: text or strings (e.g., "Hello").
- bool: True or False values.
Long Example — Student Profile
Imagine you are saving a student's details: name, age, height, and whether they passed. In Python
we use variables for this:
name = "Aisha" # str
age = 13 # int
height = 4.8 # float (in feet)
passed = True # bool
print(name + " is " + str(age) + " years old.")
Explanation (step-by-step):
- name stores text, so it is a string. We join strings using +, but to combine numbers or booleans with
strings we often convert them using str().
- age stores a number; you can do math with this value.
- passed stores True or False; you can use it in conditions.
Classwork
1. Create variables to store your name, class, and favorite subject. Print a sentence using them.
2. Store two numbers and print their multiplication.
3. Ask the user for their age and print: "Next year you will be ."
Homework
1. Ask the user for their birth year and calculate their age this year.
2. Ask the user for two numbers and print their average.
Week 3 — Operators
Definition — Arithmetic Operators
Arithmetic operators perform math: + (add), - (subtract), * (multiply), / (divide), % (remainder). Use
them to calculate totals, averages, and more.
Definition — Comparison & Logical Operators
Comparison operators compare values and return True or False: ==, !=, >, <, >=, <=. Logical
operators (and, or, not) combine comparisons.
Long Example — Marks and Decision
Suppose you have marks for three subjects and want to find the total, average and whether the
student passed.
math = 78
science = 85
english = 69
total = math + science + english
average = total / 3
passed = (average >= 40) and (math >= 33) # require 40 average and 33 in math
print("Total:", total)
print("Average:", average)
if passed:
print("Student passed!")
else:
print("Student needs improvement.")
Explanation:
- We used + to add scores and / to get average.
- The comparison average >= 40 returns True if the average is 40 or more.
- Combining conditions with and checks both rules (average and math minimum).
Classwork
1. Ask for two numbers and compute sum, difference, product, division and remainder.
2. Ask for a student's marks and check if marks >= 50.
3. Ask two boolean questions and print True only if both are True.
Homework
1. Ask three numbers and print the largest one.
2. Ask for a number and check if it is divisible by both 3 and 5.
Week 4 — Control Flow (If / Elif / Else)
Definition — If Statement
The if statement lets the program make decisions: if a condition is true, run a block of code. Use it to
choose between actions.
Definition — Elif & Else
Use elif to check another condition when the first is false, and else to run code when all previous
conditions are false.
Long Example — Age Checker and Grading
Example 1 — Voting age:
age = int(input("Enter your age: "))
if age >= 18:
print("You can vote.")
else:
print("You cannot vote yet.")
Example 2 — Grading system:
marks = int(input("Enter total marks: "))
if marks >= 90:
grade = 'A+'
elif marks >= 75:
grade = 'A'
elif marks >= 50:
grade = 'B'
else:
grade = 'C'
print("Your grade is:", grade)
Explanation:
- The first program checks one condition: age >= 18.
- The grading example shows a chain of checks. Python evaluates top to bottom and runs the first
True branch.
Classwork
1. Ask a number and print whether it is even or odd.
2. Ask marks out of 100 and assign grade using if/elif/else.
3. Ask for temperature and print: Cold if <15, Warm if 15–25, Hot if >25.
Homework
1. Ask the user for a year and check if it is a leap year (hint: divisible by 4, but not by 100 unless by
400).
2. Ask for 3 subject marks and check if the student passed all subjects (>=33 each).
Week 5 — While Loops
Definition — While Loop
A while loop repeats a block of code as long as a condition remains True. Use it when the number of
repetitions is not known in advance or you want to repeat until a condition changes.
Long Example — Number Guessing Game
We will make a small guessing game. The program chooses a number and the user keeps trying until
correct.
secret = 7
guess = None
while guess != secret:
guess = int(input("Guess a number between 1 and 10: "))
if guess < secret:
print("Too low! Try again.")
elif guess > secret:
print("Too high! Try again.")
else:
print("Correct! You guessed it.")
Explanation:
- The while loop keeps asking until guess equals secret.
- Inside loop we guide the user with hints: too low or too high.
Classwork
1. Print numbers from 1 to 10 using while.
2. Sum numbers from 1 to 100 using a loop.
3. Create a simple menu that repeats until the user types 'exit'.
Homework
1. Create a countdown timer that prints 5,4,3,2,1,Launch! (use sleep if allowed).
2. Make a program asking for positive numbers and stops when user types 0, then prints the sum.
Week 6 — For Loops & Nested Loops
Definition — For Loop
A for loop repeats code a fixed number of times, typically iterating over a sequence (like a list or
range of numbers). Use for when you know the number of repetitions or are looping over items.
Long Example — Times Table and Patterns
Example 1 — Multiplication table for 7:
n=7
for i in range(1, 11):
print(n, 'x', i, '=', n * i)
Output shows lines from 7 x 1 = 7 up to 7 x 10 = 70.
Example 2 — Star pattern using nested loops:
for row in range(1, 5):
for col in range(row):
print('*', end='')
print() # move to next line
This prints:
*
**
***
****
Explanation:
- Outer loop controls the rows; inner loop prints stars for each row. Nested loops are useful for
patterns and table-like outputs.
Classwork
1. Print numbers from 1 to 50 using for and range.
2. Print squares of numbers 1–10.
3. Create a pattern of numbers using nested loops.
Homework
1. Print a multiplication table for a user-provided number.
2. Print a 5x5 grid of numbers where each row shows 1 to 5.
Week 7 — Functions (Defining & Using)
Definition — Function
A function is a named block of code that performs a specific task. Functions help organize code,
avoid repetition, and make programs easier to read. You can pass inputs (parameters) to functions
and get results (return values).
Long Example — Making a Reusable Calculator
Let's write small functions to add and multiply:
def add(a, b):
return a + b
def multiply(a, b):
return a * b
# Use the functions
x = add(5, 3) # returns 8
y = multiply(4, 6) # returns 24
print("Sum:", x)
print("Product:", y)
Step-by-step:
1) A function starts with def and a name.
2) Parameters inside () are inputs.
3) return sends back a value to the caller.
Classwork
1. Create a function to greet a user by name.
2. Create a function that calculates the area of a rectangle.
3. Create a function that checks if a number is even.
Homework
1. Write a function to compute factorial of a number using recursion or loop.
2. Create a function that returns the largest number in a list passed to it.
Week 8 — Mini Project: Math Helper (Design & Build)
Definition — Mini Project Purpose
A mini project helps students combine multiple topics (loops, functions, input/output) into one useful
program. It teaches planning, coding, testing, and sharing results.
Long Example — Math Helper Program Plan
Goal: Make a menu-based program that helps with multiplication tables, basic calculator, and area
calculations.
Program skeleton:
def show_menu():
print("1. Multiplication Table")
print("2. Calculator")
print("3. Area of Rectangle")
print("4. Exit")
while True:
show_menu()
choice = input("Choose option: ")
if choice == '1':
n = int(input("Enter number: "))
for i in range(1, 11):
print(n, 'x', i, '=', n*i)
elif choice == '2':
# call calculator function
pass
elif choice == '3':
# call area function
pass
elif choice == '4':
break
Explanation:
- Break the project into small functions: one for menu, one for tables, one for calculator.
- Test each part separately before combining.
Classwork
1. Write the show_menu function and display options.
2. Implement multiplication table option.
3. Implement rectangle area option.
Homework
1. Implement the calculator option (add, subtract, multiply, divide).
2. Add input validation (handle wrong input gracefully).
Week 9 — Strings (Deep Dive)
Definition — String
A string is a sequence of characters (letters, numbers, symbols) enclosed in quotes. Strings let us
work with text: names, sentences, messages. Python provides many methods to change and analyze
strings.
Long Example — Working with Names
Imagine you have a student's name and want to show a friendly message and some facts:
name = "Rima Khan"
print("First letter:", name[0]) # indexing
print("Last letter:", name[-1])
print("Upper:", [Link]())
print("Lower:", [Link]())
print("Number of characters:", len(name))
# Slicing first name
first_name = [Link]()[0]
print("Hello,", first_name)
Long Example — Reverse and Palindrome Check
word = input("Enter a word: ")
rev = word[::-1] # slice trick to reverse
if [Link]() == [Link]():
print("This word is a palindrome!")
else:
print("Not a palindrome.")
Classwork
1. Ask for your full name and print first and last name separately.
2. Convert a sentence to uppercase and show the number of words.
3. Check if a word is a palindrome.
Homework
1. Replace all vowels in a string with '*' and print result.
2. Count how many times a letter appears in a given sentence.
Week 10 — Lists (Working with Collections)
Definition — List
A list is an ordered collection of items (numbers, strings, or other lists). Lists are written inside square
brackets []. They are mutable — you can change, add or remove items.
Long Example — Class Marks
marks = [78, 85, 69, 90, 55]
# Print all marks
for m in marks:
print(m)
# Add a mark
[Link](88)
# Sort marks
[Link]()
print("Sorted:", marks)
# Find highest and average
highest = max(marks)
avg = sum(marks) / len(marks)
print("Highest:", highest)
print("Average:", avg)
Explanation:
- append() adds a new item to the end.
- sort() arranges from small to large.
- max(), sum() are useful built-in functions.
Classwork
1. Create a list of 5 of your favorite games and print each one.
2. Ask user for 5 numbers, store in list and print their average.
3. Remove an item from a list and show updated list.
Homework
1. Given a list of names, print the name with the most characters.
2. Merge two lists and remove duplicates.
Week 11 — Tuples & Dictionaries
Definition — Tuple
A tuple is like a list but cannot be changed (immutable). Tuples are written using parentheses (). They
are useful for fixed collections like coordinates or days of the week.
Definition — Dictionary
A dictionary stores data as key-value pairs inside curly braces {}. Use keys to find values quickly. For
example, student names to marks.
Long Example — Contact Book with Dictionary
contacts = {"Ali": "0300-111222", "Maya": "0301-333444"}
# Add a new contact
contacts["Raza"] = "0302-555666"
# Get a number
number = [Link]("Ali")
print("Ali's number:", number)
# List all contacts
for name, num in [Link]():
print(name, "->", num)
Explanation:
- Use keys like 'Ali' to access phone numbers quickly.
- get() returns None if key not found (safe access).
Classwork
1. Create a tuple of days in a week and print Wednesday.
2. Make a dictionary of 3 students and their marks, then print Sara's marks.
3. Update a value in a dictionary.
Homework
1. Convert a list of pairs into a dictionary.
2. Count frequency of words in a short sentence using a dictionary.
Week 12 — File Handling (Read/Write)
Definition — File Handling
File handling means reading from and writing to files stored on disk. Files let programs save
information permanently (even after the program ends). Common modes: 'w' write (create), 'r' read, 'a'
append.
Long Example — Saving Student Names
# Write names to file
f = open('[Link]', 'w')
[Link]('Ali\n')
[Link]('Sara\n')
[Link]()
# Read names back
f = open('[Link]', 'r')
content = [Link]()
print(content)
[Link]()
Explanation:
- 'w' creates or clears a file and writes new content.
- 'a' adds to the end without deleting existing data.
- Always close files after use (or use with open(...) as f: which closes automatically).
Classwork
1. Create a text file and write 5 lines in it, then read and print them.
2. Append a new student name to the file and show updated content.
3. Use with open(...) as f: to read a file safely.
Homework
1. Save marks for 5 students in a file, then read and calculate the average.
2. Create or append to a log file every time the program runs (write the current time).
Week 13 — Error Handling & Debugging
Definition — Errors and Exceptions
Errors (exceptions) happen when something goes wrong in a program (wrong input, missing file,
wrong operation). Handling errors prevents the program from crashing and allows us to show friendly
messages.
Long Example — Using try/except
Try converting user input to a number:
try:
x = int(input("Enter a number: "))
print("You entered", x)
except ValueError:
print("That's not a valid number!")
# Example: handle division by zero
try:
a = int(input("a: "))
b = int(input("b: "))
print(a / b)
except ZeroDivisionError:
print("Cannot divide by zero.")
except Exception as e:
print("Some other error:", e)
Debugging Tips:
- Read error messages carefully — they tell where the problem is.
- Use print statements to check variable values.
- Test small parts of your program one by one.
Classwork
1. Write code to divide two numbers and handle invalid input.
2. Handle file not found error when reading a file.
3. Practice reading a stack trace and locating the error line.
Homework
1. Create a program that asks for a filename and tries to open it, printing a friendly message if file is
missing.
2. Intentionally create a bug in a small program and then fix it — write a short note about the bug and
fix.
Week 14 — Modules & Libraries
Definition — Modules & Libraries
Modules are files containing Python code (functions, classes) that you can reuse using import.
Libraries are collections of modules that add extra features (math, random, datetime etc.). They help
us avoid writing common code again.
Long Example — Using math, random and datetime
import math
print("Square root of 81:", [Link](81))
import random
print("Random number 1-6:", [Link](1,6)) # dice roll
from datetime import datetime
print("Today is:", [Link]().strftime('%Y-%m-%d %H:%M'))
Explanation:
- [Link] gives square root.
- [Link] picks a random integer between two numbers (useful for games).
- datetime helps with dates and times (timestamps, logs).
Classwork
1. Use random to shuffle a list of names and print the new order.
2. Use math to compute ceiling and floor of a number.
3. Print today's date in a readable format.
Homework
1. Create a small dice-rolling game that asks how many dice to roll and shows the results.
2. Use datetime to write a log entry with the current date/time into a file.
Week 15 — Revision & Problem Solving
Purpose — Revision
This week we practice problems that use many concepts together: variables, loops, conditions, lists,
functions. Problem solving improves logical thinking and prepares for the final project.
Practice Problems (with hints)
1) Find prime numbers between 2 and 100. (Hint: use loops and break early when divisible.)
2) Simple Calculator — make a menu that does add, subtract, multiply, divide. (Hint: write separate
functions for each operation.)
3) Student Report — read 5 students' names and marks into a list of dictionaries and print the
student with highest marks. (Hint: use dictionaries and max function.)
Classwork
1. Solve the prime numbers problem in class.
2. Work in pairs to build the simple calculator menu.
3. Review previous quizzes and fix mistakes.
Homework
1. Complete one extra practice problem from a list (Fibonacci sequence, palindrome list, matrix sum).
2. Prepare for the final project: write a short plan and list required features.
Week 16 — Final Project & Presentation
Definition — Final Project
A final project is a chance to use everything learned: plan, code, test, and present a working program.
Projects help students show creativity and problem solving.
Project Ideas & Guidance
1) Student Report Card — Input names and marks, compute totals and grades, save to file.
2) Library System — Add books, search books, borrow/return (manage a list/dict).
3) Rock-Paper-Scissors Game — Use random to play against computer and track score.
Project Checklist (what to include)
- Clear input and output.
- Use functions to organize code.
- Validate user input (e.g., no negative marks).
- Use files to save results (optional).
- Include comments and user instructions.
Classwork
1. Show project plan and progress to the teacher for feedback.
2. Work on project code in class and perform testing.
3. Create a short demo that runs in under 5 minutes.
Homework
1. Finish the project and test it with different inputs.
2. Prepare a one-page note describing the program logic and how it works for presentation day.