By Igbojionu Chukwudi for AIGE
HOW THIS BOOK WORKS
This book is designed as a hybrid learning guide.
Instead of teaching Python by days, it is structured around:
- Real-world problems
- Skills required to solve them
- Practical examples and mini projects
Each chapter builds on the previous one.
You may complete:
- One chapter per day
- Multiple chapters per week
- Or learn entirely at your own pace
All examples, explanations, and code are written for absolute beginners.
TABLE OF CONTENTS
- Chapter 1 – Python Foundations
- Chapter 2 – Working With User Data
- Chapter 3 – Decision Making With Code
- Chapter 4 – Automating Repetitive Tasks
- Chapter 5 – Managing Collections of Data
- Chapter 6 – Writing Reusable & Clean Code
- Chapter 7 – Building a Complete Python Application
CHAPTER 1 — PYTHON FOUNDATIONS
Problem This Solves
How do we communicate clear instructions to a computer?
What you'll learn in this chapter
By the end of this chapter you should be able to:
- Understand what Python is (and why it's popular)
- Run Python code on your computer
- Use
print()to display output - Write comments
- Create variables (store information)
- Follow basic naming rules
1) What is Python?
Python is a programming language you use to tell a computer what to do.
Python is used for:
- Websites (Django, Flask)
- Data & AI (Pandas, NumPy, ML)
- Automation (scripts that save time)
- Apps and tools (simple programs)
Python is beginner-friendly because it reads almost like English.
2) How to Run Python (3 common ways)
Option A: Python Interactive Mode (REPL)
Open your terminal/cmd and type:
python
You’ll see >>> then you can type code directly:
>>> print("Hello")
Hello
To exit:
exit()
Option B: Run a .py file
Create a file like day1.py and run:
python day1.py
Option C: VS Code / Cursor
- Install Python extension
- Create
day1.py - Click Run ▶️
3) Your First Python Program (print)
What print() does
print() tells Python: show this on the screen.
print("Hello, world!")
Code explanation
-
printis a function -
()means “call/execute the function” -
"Hello, world!"is a string (text) - Strings usually sit inside quotes
" "or' '
4) Comments (Notes Python will ignore)
Comments help you remember what your code does.
Single-line comment
# This is a comment
print("This line will run")
Why comments matter
If you come back after 1 week, comments help you understand your own code.
5) Variables (Storing information)
A variable is like a container that stores a value.
Example:
name = "Jane"
age = 17
Explanation
-
nameis the variable name -
=means “store this value inside the variable” -
"Jane"is stored inname -
17is stored inage
6) Common Data Types
String (text)
business_name = "Snap Pro"
Integer (whole number)
items_in_stock = 25
Float (number with decimal)
price = 2500.50
Boolean (True/False)
is_open = True
7) Printing Variables (Combining text + variables)
Method 1: Comma separation (easy)
name = "Jane"
print("Hello", name)
Explanation: Python automatically adds a space between items.
Method 2: f-strings (modern and clean ✅)
name = "Jane"
age = 17
print(f"My name is {name} and I am {age} years old.")
Explanation of f-string
- The
fbefore the string enables formatting -
{name}inserts the variable value inside the text - It’s the most common style in modern Python
8) Variable Naming Rules (Important!)
✅ Valid:
first_name = "Jane"
age2 = 20
total_sales = 5000
❌ Invalid:
2age = 20 # cannot start with number
my-name = "A" # dash is not allowed
class = "test" # reserved keyword
Quick rule
- Start with a letter or
_ - Use
_for spaces (snake_case) - Don’t use Python reserved words (like
class,def,if)
9) Real-Life Task: Personal Profile Script ✅
Task
Write a script that prints your:
- Full name
- Business name
- Location
- Skill
- A short message
Full Code (Day1 Project)
# Day 1 Project: Personal Profile Script
full_name = "Jane"
business_name = "Snap Pro"
location = "Nigeria"
skill = "Django development"
print("=== MY PROFILE ===")
print("Full name:", full_name)
print("Business name:", business_name)
print("Location:", location)
print("Skill:", skill)
print("\nMessage:")
print(f"Hi, I'm {full_name}. I build digital solutions with {skill}.")
Code walkthrough
- The first 4 lines create variables to store info
-
print("=== MY PROFILE ===")prints a title -
\nmeans new line (it drops to the next line) - The last line uses an f-string to combine text + variables nicely
10) Practice Exercises
- Create variables for:
- Your favorite food
- Your favorite app
- Your dream country
- Print them in a neat format.
- Change your variables and run again.
Example:
food = "Jollof rice"
app = "Instagram"
country = "Canada"
print(f"My favorite food is {food}.")
print(f"My favorite app is {app}.")
print(f"I would love to visit {country}.")
Mini Challenge (Optional ⭐)
Make your script look nicer:
- Add separators like
---------- - Add emojis inside print (Python supports it)
print("🔥 Welcome to my profile 🔥")
print("--------------------------")
CHAPTER 2 — WORKING WITH USER DATA
Problem This Solves
How do programs collect information from users and work with it?
What you'll learn in this chapter
By the end of this chapter, you will be able to:
- Understand user input
- Accept data from users
- Convert input to numbers
- Perform calculations
- Build simple real-life interactive programs
1️⃣ Understanding input()
What is input()?
input() allows your program to receive information from the user while it’s running.
Example:
name = input("Enter your name: ")
print("Hello", name)
Explanation
- Python pauses and waits for the user
- Whatever the user types becomes a string
- The value is stored in
name
⚠️ Important rule:
input()ALWAYS returns a string
2️⃣ Strings vs Numbers (Very Important)
Example
age = input("Enter your age: ")
print(age)
Even if the user types 25, Python sees it as:
"25" ← string, not number
Why this matters
You cannot do math with strings.
❌ This will cause an error:
age = input("Enter age: ")
next_year = age + 1
3️⃣ Type Conversion (Casting)
Convert string to number
age = int(input("Enter age: "))
print(age + 1)
Common conversions
| Function | Converts to |
|---|---|
int() |
Whole numbers |
float() |
Decimal numbers |
str() |
Text |
4️⃣ Practical Example: Simple Calculator
num1 = int(input("Enter first number: "))
num2 = int(input("Enter second number: "))
total = num1 + num2
print("Total:", total)
Code explanation
- User enters two numbers
-
int()converts them - Python adds them
- Result is printed
5️⃣ Basic Math Operators
| Operator | Meaning |
|---|---|
+ |
Addition |
- |
Subtraction |
* |
Multiplication |
/ |
Division |
// |
Whole division |
% |
Remainder |
** |
Power |
Example
price = 2500
qty = 3
print(price * qty) # 7500
6️⃣ Real-Life Example: Product Total Price
product = input("Product name: ")
price = float(input("Price per item: "))
quantity = int(input("Quantity: "))
total = price * quantity
print(f"\nProduct: {product}")
print(f"Total cost: ₦{total}")
Explanation
-
float()allows decimal prices -
int()ensures quantity is a whole number -
f-stringformats output nicely
7️⃣ Mini Project: POS (Point of Sale) Calculator ✅
Task
Build a small POS system that:
- Accepts product name
- Accepts price
- Accepts quantity
- Calculates total amount
- Displays receipt-like output
Full Code (Day 2 Project)
print("=== SIMPLE POS SYSTEM ===")
product_name = input("Enter product name: ")
price = float(input("Enter product price: "))
quantity = int(input("Enter quantity: "))
total = price * quantity
print("\n--- RECEIPT ---")
print(f"Product: {product_name}")
print(f"Price: ₦{price}")
print(f"Quantity: {quantity}")
print(f"Total Amount: ₦{total}")
8️⃣ Code Walkthrough (Line by Line)
print("=== SIMPLE POS SYSTEM ===")
Prints a title.
product_name = input("Enter product name: ")
Receives product name as text.
price = float(input("Enter product price: "))
Converts user input to decimal number.
quantity = int(input("Enter quantity: "))
Converts user input to whole number.
total = price * quantity
Calculates total cost.
print(f"Total Amount: ₦{total}")
Displays final result using f-string.
9️⃣ Common Beginner Mistakes ⚠️
❌ Forgetting conversion:
price = input("Price: ")
print(price * 2) # wrong
✅ Correct:
price = float(input("Price: "))
print(price * 2)
🔁 Practice Exercises (Do All)
1️⃣ Ask user for:
- Name
- Year of birth
2️⃣ Calculate:
- Current age
year = int(input("Enter year of birth: "))
age = 2026 - year
print(f"You are {age} years old")
3️⃣ Modify POS to include:
- Customer name
- Discount (optional)
⭐ Mini Challenge
Add a 10% discount automatically if total is above ₦20,000.
if total > 20000:
discount = total * 0.10
total -= discount
(Don’t worry if if looks new — you’ll master it on Day 3.)
✅ Chapter 2 Outcome
✔ You can collect real data
✔ You understand data types
✔ You can perform calculations
✔ You've built an interactive program
CHAPTER 3 — DECISION MAKING WITH CODE
Problem This Solves
How does software decide approval, rejection, or status?
🎯 What you'll learn in this chapter
By the end of this chapter, you will be able to:
- Make your program think and decide
- Use
if,elif, andelse - Compare values correctly
- Build logic for real-life situations (approval, rejection, status checks)
1️⃣ What Are Conditions?
Conditions allow your program to make decisions based on data.
Real-life examples:
- If balance is enough → allow payment
- If age ≥ 18 → allow registration
- If stock is 0 → show “Out of stock”
In Python, we do this using:
if
elif
else
2️⃣ The if Statement (Basic Decision)
Example
age = 20
if age >= 18:
print("You are allowed")
Explanation
- Python checks the condition:
age >= 18 - If it is True, the code inside runs
- If it is False, Python skips it
⚠️ Indentation matters
- Everything inside
ifmust be indented (usually 4 spaces)
3️⃣ if and else (Two Possible Outcomes)
Example
balance = 3000
if balance >= 5000:
print("Transaction approved")
else:
print("Insufficient funds")
Explanation
- Python checks the condition
- If True → runs
ifblock - If False → runs
elseblock
4️⃣ Comparison Operators (Very Important)
| Operator | Meaning |
|---|---|
== |
Equal to |
!= |
Not equal |
> |
Greater than |
< |
Less than |
>= |
Greater or equal |
<= |
Less or equal |
Example
score = 75
if score >= 50:
print("Passed")
else:
print("Failed")
5️⃣ Using elif (Multiple Conditions)
Example
score = 85
if score >= 80:
print("Grade A")
elif score >= 60:
print("Grade B")
elif score >= 50:
print("Grade C")
else:
print("Failed")
Explanation
- Python checks from top to bottom
- The first true condition runs
- Others are ignored
6️⃣ Conditions with User Input
Example
age = int(input("Enter your age: "))
if age >= 18:
print("You are eligible")
else:
print("You are not eligible")
Explanation
- User input is converted to
int - Python compares the value
- Decision is made automatically
7️⃣ Real-Life Example: Business Discount Logic
amount = float(input("Enter total amount: "))
if amount >= 20000:
discount = amount * 0.10
print(f"Discount applied: ₦{discount}")
else:
print("No discount applied")
Explanation
- If customer spends enough → reward them
- Else → normal pricing
8️⃣ Mini Project: Loan Eligibility Checker ✅
Task
Build a program that:
- Asks for monthly income
- Approves loan if income ≥ ₦100,000
- Rejects otherwise
- Shows clear message
Full Code (Day 3 Project)
print("=== LOAN ELIGIBILITY CHECKER ===")
income = float(input("Enter your monthly income: ₦"))
if income >= 100000:
print("✅ Loan Approved")
print("You qualify for the loan.")
else:
print("❌ Loan Rejected")
print("Income below required threshold.")
9️⃣ Code Walkthrough (Line by Line)
print("=== LOAN ELIGIBILITY CHECKER ===")
Displays program title.
income = float(input("Enter your monthly income: ₦"))
- Receives income
- Converts to number
if income >= 100000:
- Condition check
print("✅ Loan Approved")
- Runs only if condition is True
else:
- Runs when condition is False
🔥 Common Beginner Errors & Fixes
❌ Using = instead of ==
if income = 100000: # wrong
✅ Correct
if income == 100000:
❌ Forgetting indentation
if income > 50000:
print("Approved") # error
✅ Correct
if income > 50000:
print("Approved")
🔁 Practice Exercises (Do All)
Exercise 1: Voting Eligibility
age = int(input("Enter your age: "))
if age >= 18:
print("You can vote")
else:
print("You cannot vote")
Exercise 2: Stock Checker
stock = int(input("Enter available stock: "))
if stock > 0:
print("Item available")
else:
print("Out of stock")
Exercise 3: Grading System
score = int(input("Enter your score: "))
if score >= 70:
print("Excellent")
elif score >= 50:
print("Good")
else:
print("Needs improvement")
⭐ Mini Challenge (Optional)
Build a Payment Status Checker
- Ask for balance
- Ask for price
- If balance ≥ price → Payment successful
- Else → Insufficient balance
balance = float(input("Balance: "))
price = float(input("Price: "))
if balance >= price:
print("Payment successful")
else:
print("Insufficient balance")
✅ Chapter 3 Outcome
✔ You can make decisions in code
✔ You understand conditions & comparisons
✔ You can build approval/rejection logic
✔ You're ready for loops
CHAPTER 4 — AUTOMATING REPETITIVE TASKS
Problem This Solves
How do we avoid doing the same work repeatedly?
🎯 What you'll learn in this chapter
By the end of this chapter, you will be able to:
- Understand what loops are
- Use
forloops andwhileloops - Repeat tasks automatically
- Build real-life programs that run multiple times
- Control when a loop stops
1️⃣ What Is a Loop?
A loop allows Python to repeat an action multiple times.
Real-life examples
- Recording daily sales for 7 days
- Printing a receipt for 10 customers
- Counting stock items
- Repeating until user says “stop”
Instead of writing code again and again, we use loops.
2️⃣ The for Loop (When You Know How Many Times)
Basic Example
for i in range(5):
print("Hello")
Explanation
-
range(5)means 0 to 4 (5 times) -
iis a counter (0, 1, 2, 3, 4) - Code inside runs 5 times
3️⃣ Understanding range()
| Code | Meaning |
|---|---|
range(5) |
0 → 4 |
range(1, 6) |
1 → 5 |
range(1, 10, 2) |
1, 3, 5, 7, 9 |
Example
for day in range(1, 6):
print("Day", day)
4️⃣ Looping Through Data (Real-Life Friendly)
products = ["Rice", "Beans", "Oil"]
for item in products:
print(item)
Explanation
- Python takes one item at a time from the list
- No need to count manually
5️⃣ Real-Life Example: Daily Sales Tracker
for day in range(1, 6):
sales = float(input(f"Enter sales for Day {day}: ₦"))
print(f"Sales recorded: ₦{sales}")
What’s happening?
- Loop runs 5 times
- Each time, user enters sales
- Python labels each day automatically
6️⃣ The while Loop (Repeat Until Condition Is False)
Basic Example
count = 1
while count <= 5:
print("Count:", count)
count += 1
Explanation
- Loop runs as long as condition is True
-
count += 1prevents infinite loop
7️⃣ Infinite Loop (⚠️ Be Careful)
while True:
print("This will run forever")
To stop it manually:
- Press Ctrl + C
8️⃣ Using break (Exit a Loop)
while True:
name = input("Enter name (or 'exit'): ")
if name == "exit":
break
print("Hello", name)
Explanation
- Loop keeps running
- Stops only when user types
exit
9️⃣ Using continue (Skip One Round)
for num in range(1, 6):
if num == 3:
continue
print(num)
Output
1
2
4
5
🔥 Mini Project: Daily Sales Recorder ✅
Task
Build a program that:
- Records sales for 7 days
- Shows total sales at the end
Full Code (Day 4 Project)
print("=== DAILY SALES RECORDER ===")
total_sales = 0
for day in range(1, 8):
sales = float(input(f"Enter sales for Day {day}: ₦"))
total_sales += sales
print("\nWeekly sales summary")
print(f"Total sales for the week: ₦{total_sales}")
🔍 Code Walkthrough (Line by Line)
total_sales = 0
Starts total at zero.
for day in range(1, 8):
Loop runs 7 times.
total_sales += sales
Adds each day’s sales to total.
⚠️ Common Beginner Mistakes
❌ Forgetting to update counter in while
count = 1
while count <= 5:
print(count)
✅ Fix
count += 1
❌ Wrong indentation
for i in range(3):
print(i)
✅ Fix
for i in range(3):
print(i)
🔁 Practice Exercises (Must Do)
Exercise 1: Print Numbers 1–10
for i in range(1, 11):
print(i)
Exercise 2: Repeat Until User Stops
while True:
msg = input("Type something (or 'stop'): ")
if msg == "stop":
break
print(msg)
Exercise 3: Sum of Numbers
total = 0
for i in range(5):
num = int(input("Enter number: "))
total += num
print("Total:", total)
⭐ Mini Challenge (Optional)
Modify the sales recorder:
- Stop early if user types
0 - Count how many days were entered
(Hint: use break and a counter)
✅ Chapter 4 Outcome
✔ You can automate repetitive tasks
✔ You understand for and while loops
✔ You can control program flow
✔ You're ready for Lists & Data Collections
CHAPTER 5 — MANAGING COLLECTIONS OF DATA
Problem This Solves
How do applications store and manage multiple records?
🎯 What you'll learn in this chapter
By the end of this chapter, you will be able to:
- Understand what lists are
- Store multiple values in one variable
- Add, remove, and access items
- Loop through lists
- Build simple real-life data management programs
1️⃣ What Is a List?
A list is a collection of items stored in one place.
Real-life examples
- List of products in a shop
- List of patients in a clinic
- List of tasks for a day
- List of customer names
Instead of creating many variables:
p1 = "Rice"
p2 = "Beans"
p3 = "Oil"
We use a list:
products = ["Rice", "Beans", "Oil"]
2️⃣ Creating a List
items = ["Bread", "Milk", "Eggs"]
print(items)
Explanation
- Square brackets
[]define a list - Items are separated by commas
- Lists can contain text, numbers, or both
3️⃣ Accessing List Items (Indexing)
products = ["Rice", "Beans", "Oil"]
print(products[0]) # Rice
print(products[1]) # Beans
print(products[2]) # Oil
Important Rule ⚠️
Python starts counting from 0, not 1.
4️⃣ Changing List Items
products = ["Rice", "Beans", "Oil"]
products[1] = "Garri"
print(products)
Explanation
- Index
1(Beans) is replaced withGarri
5️⃣ Adding Items to a List
Using append() (most common)
products = ["Rice", "Beans"]
products.append("Oil")
print(products)
Explanation
- Adds item to the end of the list
6️⃣ Removing Items from a List
Remove by name
products.remove("Beans")
Remove last item
products.pop()
7️⃣ List Length (len())
products = ["Rice", "Beans", "Oil"]
print(len(products)) # 3
Real-life use
- Count number of items in stock
- Count number of customers
- Count number of days recorded
8️⃣ Looping Through a List (Very Important)
products = ["Rice", "Beans", "Oil"]
for item in products:
print(item)
Explanation
- Python picks each item one by one
- Cleaner than using indexes manually
9️⃣ Lists with User Input (Dynamic Data)
items = []
for i in range(3):
product = input("Enter product name: ")
items.append(product)
print(items)
Explanation
- Starts with an empty list
- User adds items dynamically
🔥 Mini Project: Inventory Manager ✅
Task
Build a program that:
- Allows user to add products
- Stores them in a list
- Displays all products
- Shows total number of products
Full Code (Day 5 Project)
print("=== INVENTORY MANAGER ===")
inventory = []
while True:
product = input("Enter product name (or 'exit'): ")
if product == "exit":
break
inventory.append(product)
print("Product added.")
print("\nInventory List:")
for item in inventory:
print("-", item)
print(f"\nTotal products: {len(inventory)}")
🔍 Code Walkthrough
inventory = []
Creates an empty list.
while True:
Keeps program running.
inventory.append(product)
Adds each product.
len(inventory)
Counts total items.
⚠️ Common Beginner Mistakes
❌ Accessing invalid index
print(products[5]) # error if list has only 3 items
✅ Fix
if len(products) > 5:
print(products[5])
❌ Forgetting quotes around strings
products.append(Rice) # wrong
✅ Fix
products.append("Rice")
🔁 Practice Exercises (Must Do)
Exercise 1: Favorite Foods
foods = []
for i in range(3):
food = input("Enter a food: ")
foods.append(food)
for f in foods:
print(f)
Exercise 2: Remove an Item
items = ["Pen", "Book", "Bag"]
items.remove("Book")
print(items)
Exercise 3: Count Items
names = ["Jane", "John", "Mary"]
print("Total names:", len(names))
⭐ Mini Challenge (Optional)
Modify Inventory Manager:
- Prevent duplicate products
- Show message if item already exists
if product in inventory:
print("Item already exists")
else:
inventory.append(product)
✅ Chapter 5 Outcome
✔ You can store multiple data values
✔ You can manage dynamic data
✔ You can loop through lists
✔ You're ready for Functions
CHAPTER 6 — WRITING REUSABLE & CLEAN CODE
Problem This Solves
How do professionals organize code for reuse?
🎯 What you'll learn in this chapter
By the end of this chapter, you will be able to:
- Understand what functions are
- Write your own functions
- Pass data into functions
- Get results back using
return - Organize code like a professional developer
1️⃣ What Is a Function?
A function is a block of code that does a specific job and can be reused.
Real-life example
Instead of calculating profit again and again:
- You create one function
- Call it whenever you need it
Think of a function like:
“A machine that takes input → does work → gives output”
2️⃣ Why Functions Are Important
Without functions:
- Code becomes long
- You repeat yourself
- Bugs are harder to fix
With functions:
- Code is cleaner
- Easier to read
- Easier to reuse
- Easier to maintain
3️⃣ Creating a Function (def)
Basic Function Example
def greet():
print("Hello, welcome!")
Explanation
-
defmeans define function -
greetis the function name -
()means no input yet - Indentation defines the function body
4️⃣ Calling a Function
greet()
greet()
Output
Hello, welcome!
Hello, welcome!
Explanation
- Function runs only when called
- You can call it many times
5️⃣ Function with Parameters (Input)
Example
def greet_user(name):
print(f"Hello {name}, welcome!")
Calling it
greet_user("Jane")
greet_user("Chuks")
Explanation
-
nameis a parameter - Value passed is called an argument
6️⃣ Function with Multiple Parameters
def add_numbers(a, b):
print(a + b)
add_numbers(5, 3)
Explanation
-
aandbreceive values - Function performs calculation
7️⃣ Using return (Very Important)
Example
def calculate_profit(cost, selling_price):
profit = selling_price - cost
return profit
Calling it
result = calculate_profit(500, 800)
print("Profit:", result)
Explanation
-
returnsends value back - Code after
returndoes NOT run - Returned value can be stored in a variable
8️⃣ Difference Between print() and return
print() |
return |
|---|---|
| Displays value | Sends value back |
| Cannot be reused | Can be reused |
| For output only | For logic |
❌ Bad practice
def total(a, b):
print(a + b)
✅ Better practice
def total(a, b):
return a + b
9️⃣ Function with User Input
def calculate_total():
price = float(input("Price: "))
qty = int(input("Quantity: "))
return price * qty
total = calculate_total()
print("Total:", total)
Explanation
- Function handles logic
- Main program handles output
🔥 Mini Project: Profit Calculator ✅
Task
Build a program that:
- Uses a function to calculate profit
- Accepts cost price and selling price
- Displays profit or loss
Full Code (Day 6 Project)
print("=== PROFIT CALCULATOR ===")
def calculate_profit(cost_price, selling_price):
return selling_price - cost_price
cost = float(input("Enter cost price: ₦"))
selling = float(input("Enter selling price: ₦"))
profit = calculate_profit(cost, selling)
if profit > 0:
print(f"Profit made: ₦{profit}")
elif profit < 0:
print(f"Loss incurred: ₦{abs(profit)}")
else:
print("No profit, no loss")
🔍 Code Walkthrough
def calculate_profit(cost_price, selling_price):
Defines function with two inputs.
return selling_price - cost_price
Calculates and returns result.
profit = calculate_profit(cost, selling)
Stores returned value.
if profit > 0:
Decision based on function result.
⚠️ Common Beginner Mistakes
❌ Forgetting to call function
calculate_profit
✅ Correct
calculate_profit(500, 700)
❌ Forgetting return
def calc(a, b):
a + b
✅ Correct
def calc(a, b):
return a + b
🔁 Practice Exercises (Must Do)
Exercise 1: Greeting Function
def welcome(name):
print(f"Welcome {name}")
welcome("Jane")
Exercise 2: Area Calculator
def area(length, width):
return length * width
print(area(5, 4))
Exercise 3: Reuse Function
def square(num):
return num * num
print(square(2))
print(square(5))
⭐ Mini Challenge (Optional)
Create a Simple POS Function
- Function to calculate total
- Function to apply discount
- Combine both
def apply_discount(amount):
if amount > 20000:
return amount * 0.9
return amount
✅ Chapter 6 Outcome
✔ You can write clean reusable code
✔ You understand functions & return values
✔ You can separate logic from output
✔ You're ready for Building a Complete Python Application
CHAPTER 7 — BUILDING A COMPLETE PYTHON APPLICATION
Problem This Solves
How do we combine all Python fundamentals into a real system?
🎯 Goal of this chapter
By the end of this chapter, you will:
- Combine input, conditions, loops, lists, and functions
- Build a real-life business-style program
- Think like a junior Python developer
- Be confident to move into Django, automation, or AI basics
🧠 What You'll Use From Previous Chapters
| Chapter | Concept |
|---|---|
| Chapter 1 | Variables, print |
| Chapter 2 | input(), numbers |
| Chapter 3 | if / else |
| Chapter 4 | loops |
| Chapter 5 | lists |
| Chapter 6 | functions |
📦 Mini Project: Simple Business Sales Manager
📝 Project Description
Build a program that:
- Records multiple product sales
- Calculates total price per product
- Stores all products sold
- Calculates total sales
- Allows user to stop when done
- Displays a final summary
This is similar to:
- A shop POS
- A sales tracker
- A basic inventory/sales system
🧱 Step 1: Plan the Program (Very Important)
We need:
- A list to store products
- A loop to keep asking for data
- A function to calculate total
- Conditions to stop the program
- A summary at the end
🧩 Step 2: Define Helper Function
def calculate_total(price, quantity):
return price * quantity
Explanation
- Takes
priceandquantity - Returns the total amount
- Reusable for every product
🔁 Step 3: Main Program Loop
Full Project Code (Day 7 Final)
print("=== SIMPLE SALES MANAGEMENT SYSTEM ===")
sales = [] # list to store sales
grand_total = 0 # total sales amount
def calculate_total(price, quantity):
return price * quantity
while True:
product = input("\nEnter product name (or 'exit'): ")
if product.lower() == "exit":
break
price = float(input("Enter price: ₦"))
quantity = int(input("Enter quantity: "))
total = calculate_total(price, quantity)
grand_total += total
sales.append(product)
print(f"Total for {product}: ₦{total}")
print("\n=== SALES SUMMARY ===")
for item in sales:
print("-", item)
print(f"\nNumber of products sold: {len(sales)}")
print(f"Grand Total Sales: ₦{grand_total}")
🔍 Full Code Walkthrough (Section by Section)
1️⃣ Program Title
print("=== SIMPLE SALES MANAGEMENT SYSTEM ===")
Displays program heading.
2️⃣ Data Storage
sales = []
grand_total = 0
-
salesstores product names -
grand_totalaccumulates total sales
3️⃣ Function Definition
def calculate_total(price, quantity):
return price * quantity
Handles calculation logic cleanly.
4️⃣ Infinite Loop
while True:
Keeps program running until user stops it.
5️⃣ Exit Condition
if product.lower() == "exit":
break
- Allows user to exit safely
-
.lower()makes input case-insensitive
6️⃣ User Input & Calculation
price = float(input("Enter price: ₦"))
quantity = int(input("Enter quantity: "))
Gets numeric input.
total = calculate_total(price, quantity)
Uses function.
7️⃣ Data Storage
sales.append(product)
grand_total += total
Stores data and updates total.
8️⃣ Final Summary Output
print("\n=== SALES SUMMARY ===")
Prints results neatly.
⚠️ Common Errors to Watch Out For
❌ Forgetting to convert input
price = input("Price: ") # wrong
✅ Correct
price = float(input("Price: "))
❌ Not using break
while True:
print("Running forever")
🔁 Practice Improvements (Do These)
1️⃣ Store price + quantity together
sales.append((product, total))
2️⃣ Prevent empty product names
if product == "":
print("Product name cannot be empty")
continue
3️⃣ Add discount logic
if total > 20000:
total *= 0.9
⭐ Mini Challenge (Advanced Beginner)
Upgrade the app to:
- Store product, price, quantity, total
- Display full receipt-style output
Example:
Rice - Qty: 2 - ₦5000
Beans - Qty: 1 - ₦3000
🎉 FINAL OUTCOME
After completing this book, you can:
✔ Write clean Python scripts
✔ Build interactive programs
✔ Use logic, loops, lists, and functions
✔ Create real-life tools for business
✔ Move confidently into Django, automation, or AI
NEXT STEPS
- Python file handling
- Error handling
- Databases
- Django web development
🎉 Congratulations
You have completed *Python Fundamentals *.
Top comments (0)