DEV Community

Cover image for PYTHON FUNDAMENTALS | From Basics to Real-World Applications
igbojionu
igbojionu

Posted on

PYTHON FUNDAMENTALS | From Basics to Real-World Applications

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

  1. Chapter 1 – Python Foundations
  2. Chapter 2 – Working With User Data
  3. Chapter 3 – Decision Making With Code
  4. Chapter 4 – Automating Repetitive Tasks
  5. Chapter 5 – Managing Collections of Data
  6. Chapter 6 – Writing Reusable & Clean Code
  7. 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
Enter fullscreen mode Exit fullscreen mode

You’ll see >>> then you can type code directly:

>>> print("Hello")
Hello
Enter fullscreen mode Exit fullscreen mode

To exit:

exit()
Enter fullscreen mode Exit fullscreen mode

Option B: Run a .py file

Create a file like day1.py and run:

python day1.py
Enter fullscreen mode Exit fullscreen mode

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!")
Enter fullscreen mode Exit fullscreen mode

Code explanation

  • print is 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")
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Explanation

  • name is the variable name
  • = means “store this value inside the variable”
  • "Jane" is stored in name
  • 17 is stored in age

6) Common Data Types

String (text)

business_name = "Snap Pro"
Enter fullscreen mode Exit fullscreen mode

Integer (whole number)

items_in_stock = 25
Enter fullscreen mode Exit fullscreen mode

Float (number with decimal)

price = 2500.50
Enter fullscreen mode Exit fullscreen mode

Boolean (True/False)

is_open = True
Enter fullscreen mode Exit fullscreen mode

7) Printing Variables (Combining text + variables)

Method 1: Comma separation (easy)

name = "Jane"
print("Hello", name)
Enter fullscreen mode Exit fullscreen mode

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.")
Enter fullscreen mode Exit fullscreen mode

Explanation of f-string

  • The f before 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
Enter fullscreen mode Exit fullscreen mode

❌ Invalid:

2age = 20         # cannot start with number
my-name = "A"     # dash is not allowed
class = "test"    # reserved keyword
Enter fullscreen mode Exit fullscreen mode

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}.")
Enter fullscreen mode Exit fullscreen mode

Code walkthrough

  • The first 4 lines create variables to store info
  • print("=== MY PROFILE ===") prints a title
  • \n means new line (it drops to the next line)
  • The last line uses an f-string to combine text + variables nicely

10) Practice Exercises

  1. Create variables for:
  • Your favorite food
  • Your favorite app
  • Your dream country
    1. Print them in a neat format.
    2. 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}.")
Enter fullscreen mode Exit fullscreen mode

Mini Challenge (Optional ⭐)

Make your script look nicer:

  • Add separators like ----------
  • Add emojis inside print (Python supports it)
print("🔥 Welcome to my profile 🔥")
print("--------------------------")
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Even if the user types 25, Python sees it as:

"25"  ← string, not number
Enter fullscreen mode Exit fullscreen mode

Why this matters

You cannot do math with strings.

❌ This will cause an error:

age = input("Enter age: ")
next_year = age + 1
Enter fullscreen mode Exit fullscreen mode

3️⃣ Type Conversion (Casting)

Convert string to number

age = int(input("Enter age: "))
print(age + 1)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

Explanation

  • float() allows decimal prices
  • int() ensures quantity is a whole number
  • f-string formats 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}")
Enter fullscreen mode Exit fullscreen mode

8️⃣ Code Walkthrough (Line by Line)

print("=== SIMPLE POS SYSTEM ===")
Enter fullscreen mode Exit fullscreen mode

Prints a title.

product_name = input("Enter product name: ")
Enter fullscreen mode Exit fullscreen mode

Receives product name as text.

price = float(input("Enter product price: "))
Enter fullscreen mode Exit fullscreen mode

Converts user input to decimal number.

quantity = int(input("Enter quantity: "))
Enter fullscreen mode Exit fullscreen mode

Converts user input to whole number.

total = price * quantity
Enter fullscreen mode Exit fullscreen mode

Calculates total cost.

print(f"Total Amount: ₦{total}")
Enter fullscreen mode Exit fullscreen mode

Displays final result using f-string.


9️⃣ Common Beginner Mistakes ⚠️

❌ Forgetting conversion:

price = input("Price: ")
print(price * 2)   # wrong
Enter fullscreen mode Exit fullscreen mode

✅ Correct:

price = float(input("Price: "))
print(price * 2)
Enter fullscreen mode Exit fullscreen mode

🔁 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")
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

(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, and else
  • 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
Enter fullscreen mode Exit fullscreen mode

2️⃣ The if Statement (Basic Decision)

Example

age = 20

if age >= 18:
    print("You are allowed")
Enter fullscreen mode Exit fullscreen mode

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 if must 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")
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Python checks the condition
  • If True → runs if block
  • If False → runs else block

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")
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

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.")
Enter fullscreen mode Exit fullscreen mode

9️⃣ Code Walkthrough (Line by Line)

print("=== LOAN ELIGIBILITY CHECKER ===")
Enter fullscreen mode Exit fullscreen mode

Displays program title.

income = float(input("Enter your monthly income: ₦"))
Enter fullscreen mode Exit fullscreen mode
  • Receives income
  • Converts to number
if income >= 100000:
Enter fullscreen mode Exit fullscreen mode
  • Condition check
print("✅ Loan Approved")
Enter fullscreen mode Exit fullscreen mode
  • Runs only if condition is True
else:
Enter fullscreen mode Exit fullscreen mode
  • Runs when condition is False

🔥 Common Beginner Errors & Fixes

❌ Using = instead of ==

if income = 100000:   # wrong
Enter fullscreen mode Exit fullscreen mode

✅ Correct

if income == 100000:
Enter fullscreen mode Exit fullscreen mode

❌ Forgetting indentation

if income > 50000:
print("Approved")  # error
Enter fullscreen mode Exit fullscreen mode

✅ Correct

if income > 50000:
    print("Approved")
Enter fullscreen mode Exit fullscreen mode

🔁 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")
Enter fullscreen mode Exit fullscreen mode

Exercise 2: Stock Checker

stock = int(input("Enter available stock: "))

if stock > 0:
    print("Item available")
else:
    print("Out of stock")
Enter fullscreen mode Exit fullscreen mode

Exercise 3: Grading System

score = int(input("Enter your score: "))

if score >= 70:
    print("Excellent")
elif score >= 50:
    print("Good")
else:
    print("Needs improvement")
Enter fullscreen mode Exit fullscreen mode

⭐ 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")
Enter fullscreen mode Exit fullscreen mode

✅ 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 for loops and while loops
  • 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")
Enter fullscreen mode Exit fullscreen mode

Explanation

  • range(5) means 0 to 4 (5 times)
  • i is 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)
Enter fullscreen mode Exit fullscreen mode

4️⃣ Looping Through Data (Real-Life Friendly)

products = ["Rice", "Beans", "Oil"]

for item in products:
    print(item)
Enter fullscreen mode Exit fullscreen mode

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}")
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Loop runs as long as condition is True
  • count += 1 prevents infinite loop

7️⃣ Infinite Loop (⚠️ Be Careful)

while True:
    print("This will run forever")
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

Output

1
2
4
5
Enter fullscreen mode Exit fullscreen mode

🔥 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}")
Enter fullscreen mode Exit fullscreen mode

🔍 Code Walkthrough (Line by Line)

total_sales = 0
Enter fullscreen mode Exit fullscreen mode

Starts total at zero.

for day in range(1, 8):
Enter fullscreen mode Exit fullscreen mode

Loop runs 7 times.

total_sales += sales
Enter fullscreen mode Exit fullscreen mode

Adds each day’s sales to total.


⚠️ Common Beginner Mistakes

❌ Forgetting to update counter in while

count = 1
while count <= 5:
    print(count)
Enter fullscreen mode Exit fullscreen mode

✅ Fix

count += 1
Enter fullscreen mode Exit fullscreen mode

❌ Wrong indentation

for i in range(3):
print(i)
Enter fullscreen mode Exit fullscreen mode

✅ Fix

for i in range(3):
    print(i)
Enter fullscreen mode Exit fullscreen mode

🔁 Practice Exercises (Must Do)

Exercise 1: Print Numbers 1–10

for i in range(1, 11):
    print(i)
Enter fullscreen mode Exit fullscreen mode

Exercise 2: Repeat Until User Stops

while True:
    msg = input("Type something (or 'stop'): ")

    if msg == "stop":
        break

    print(msg)
Enter fullscreen mode Exit fullscreen mode

Exercise 3: Sum of Numbers

total = 0

for i in range(5):
    num = int(input("Enter number: "))
    total += num

print("Total:", total)
Enter fullscreen mode Exit fullscreen mode

⭐ 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"
Enter fullscreen mode Exit fullscreen mode

We use a list:

products = ["Rice", "Beans", "Oil"]
Enter fullscreen mode Exit fullscreen mode

2️⃣ Creating a List

items = ["Bread", "Milk", "Eggs"]
print(items)
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Important Rule ⚠️

Python starts counting from 0, not 1.


4️⃣ Changing List Items

products = ["Rice", "Beans", "Oil"]
products[1] = "Garri"

print(products)
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Index 1 (Beans) is replaced with Garri

5️⃣ Adding Items to a List

Using append() (most common)

products = ["Rice", "Beans"]
products.append("Oil")

print(products)
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Adds item to the end of the list

6️⃣ Removing Items from a List

Remove by name

products.remove("Beans")
Enter fullscreen mode Exit fullscreen mode

Remove last item

products.pop()
Enter fullscreen mode Exit fullscreen mode

7️⃣ List Length (len())

products = ["Rice", "Beans", "Oil"]
print(len(products))  # 3
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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)}")
Enter fullscreen mode Exit fullscreen mode

🔍 Code Walkthrough

inventory = []
Enter fullscreen mode Exit fullscreen mode

Creates an empty list.

while True:
Enter fullscreen mode Exit fullscreen mode

Keeps program running.

inventory.append(product)
Enter fullscreen mode Exit fullscreen mode

Adds each product.

len(inventory)
Enter fullscreen mode Exit fullscreen mode

Counts total items.


⚠️ Common Beginner Mistakes

❌ Accessing invalid index

print(products[5])  # error if list has only 3 items
Enter fullscreen mode Exit fullscreen mode

✅ Fix

if len(products) > 5:
    print(products[5])
Enter fullscreen mode Exit fullscreen mode

❌ Forgetting quotes around strings

products.append(Rice)  # wrong
Enter fullscreen mode Exit fullscreen mode

✅ Fix

products.append("Rice")
Enter fullscreen mode Exit fullscreen mode

🔁 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)
Enter fullscreen mode Exit fullscreen mode

Exercise 2: Remove an Item

items = ["Pen", "Book", "Bag"]
items.remove("Book")
print(items)
Enter fullscreen mode Exit fullscreen mode

Exercise 3: Count Items

names = ["Jane", "John", "Mary"]
print("Total names:", len(names))
Enter fullscreen mode Exit fullscreen mode

⭐ 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)
Enter fullscreen mode Exit fullscreen mode

✅ 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!")
Enter fullscreen mode Exit fullscreen mode

Explanation

  • def means define function
  • greet is the function name
  • () means no input yet
  • Indentation defines the function body

4️⃣ Calling a Function

greet()
greet()
Enter fullscreen mode Exit fullscreen mode

Output

Hello, welcome!
Hello, welcome!
Enter fullscreen mode Exit fullscreen mode

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!")
Enter fullscreen mode Exit fullscreen mode

Calling it

greet_user("Jane")
greet_user("Chuks")
Enter fullscreen mode Exit fullscreen mode

Explanation

  • name is 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)
Enter fullscreen mode Exit fullscreen mode

Explanation

  • a and b receive values
  • Function performs calculation

7️⃣ Using return (Very Important)

Example

def calculate_profit(cost, selling_price):
    profit = selling_price - cost
    return profit
Enter fullscreen mode Exit fullscreen mode

Calling it

result = calculate_profit(500, 800)
print("Profit:", result)
Enter fullscreen mode Exit fullscreen mode

Explanation

  • return sends value back
  • Code after return does 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)
Enter fullscreen mode Exit fullscreen mode

✅ Better practice

def total(a, b):
    return a + b
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

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")
Enter fullscreen mode Exit fullscreen mode

🔍 Code Walkthrough

def calculate_profit(cost_price, selling_price):
Enter fullscreen mode Exit fullscreen mode

Defines function with two inputs.

return selling_price - cost_price
Enter fullscreen mode Exit fullscreen mode

Calculates and returns result.

profit = calculate_profit(cost, selling)
Enter fullscreen mode Exit fullscreen mode

Stores returned value.

if profit > 0:
Enter fullscreen mode Exit fullscreen mode

Decision based on function result.


⚠️ Common Beginner Mistakes

❌ Forgetting to call function

calculate_profit
Enter fullscreen mode Exit fullscreen mode

✅ Correct

calculate_profit(500, 700)
Enter fullscreen mode Exit fullscreen mode

❌ Forgetting return

def calc(a, b):
    a + b
Enter fullscreen mode Exit fullscreen mode

✅ Correct

def calc(a, b):
    return a + b
Enter fullscreen mode Exit fullscreen mode

🔁 Practice Exercises (Must Do)

Exercise 1: Greeting Function

def welcome(name):
    print(f"Welcome {name}")

welcome("Jane")
Enter fullscreen mode Exit fullscreen mode

Exercise 2: Area Calculator

def area(length, width):
    return length * width

print(area(5, 4))
Enter fullscreen mode Exit fullscreen mode

Exercise 3: Reuse Function

def square(num):
    return num * num

print(square(2))
print(square(5))
Enter fullscreen mode Exit fullscreen mode

⭐ 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
Enter fullscreen mode Exit fullscreen mode

✅ 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
Enter fullscreen mode Exit fullscreen mode

Explanation

  • Takes price and quantity
  • 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}")
Enter fullscreen mode Exit fullscreen mode

🔍 Full Code Walkthrough (Section by Section)


1️⃣ Program Title

print("=== SIMPLE SALES MANAGEMENT SYSTEM ===")
Enter fullscreen mode Exit fullscreen mode

Displays program heading.


2️⃣ Data Storage

sales = []
grand_total = 0
Enter fullscreen mode Exit fullscreen mode
  • sales stores product names
  • grand_total accumulates total sales

3️⃣ Function Definition

def calculate_total(price, quantity):
    return price * quantity
Enter fullscreen mode Exit fullscreen mode

Handles calculation logic cleanly.


4️⃣ Infinite Loop

while True:
Enter fullscreen mode Exit fullscreen mode

Keeps program running until user stops it.


5️⃣ Exit Condition

if product.lower() == "exit":
    break
Enter fullscreen mode Exit fullscreen mode
  • Allows user to exit safely
  • .lower() makes input case-insensitive

6️⃣ User Input & Calculation

price = float(input("Enter price: ₦"))
quantity = int(input("Enter quantity: "))
Enter fullscreen mode Exit fullscreen mode

Gets numeric input.

total = calculate_total(price, quantity)
Enter fullscreen mode Exit fullscreen mode

Uses function.


7️⃣ Data Storage

sales.append(product)
grand_total += total
Enter fullscreen mode Exit fullscreen mode

Stores data and updates total.


8️⃣ Final Summary Output

print("\n=== SALES SUMMARY ===")
Enter fullscreen mode Exit fullscreen mode

Prints results neatly.


⚠️ Common Errors to Watch Out For

❌ Forgetting to convert input

price = input("Price: ")  # wrong
Enter fullscreen mode Exit fullscreen mode

✅ Correct

price = float(input("Price: "))
Enter fullscreen mode Exit fullscreen mode

❌ Not using break

while True:
    print("Running forever")
Enter fullscreen mode Exit fullscreen mode

🔁 Practice Improvements (Do These)

1️⃣ Store price + quantity together

sales.append((product, total))
Enter fullscreen mode Exit fullscreen mode

2️⃣ Prevent empty product names

if product == "":
    print("Product name cannot be empty")
    continue
Enter fullscreen mode Exit fullscreen mode

3️⃣ Add discount logic

if total > 20000:
    total *= 0.9
Enter fullscreen mode Exit fullscreen mode

⭐ 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
Enter fullscreen mode Exit fullscreen mode

🎉 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)