TOPFAITH UNIVERSITY,
MKPATAK, AKWA IBOM STATE, NIGERIA.
COURSE TITLE: Introduction to Python Programmin
COURSE CODE: TUM-GET 214
Comprehensive Lesson Notes & Workbook
A complete guide covering basics to functions, including practical examples and a practice workbook.
Learning Objectives
The Objectives of this course are to;
1. describe the basic syntax and structure of the Python programming language;
2. use variables, data types, and control structures to write simple Python programs;
3. write and call functions in Python;
4. read and write data to files using Python;
5. apply the principles of object-oriented programming in Python;
6. utilize Python libraries to perform basic data analysis and visualization.
Learning Outcomes:
At the end of the course students should be able to learn the following:
1. install and Run a Python program using IDLE or Python shell;
2. write a simple Python program;
3. utilize CSV and JSON file formats in Python;
4. develop a basic Flask application;
5. work with arrays and data frames in NumPy and Pandas;
6. visualize data using Matplotlib in Python.
Module 1: Introduction & Setup
1. Introduction to Python and its uses
Python is a high-level, interpreted programming language known for its readability and simplicity.
Created by Guido van Rossum and released in 1991, Python supports multiple programming paradigms,
including procedural, object-oriented, and functional programming.
Uses of Python:
- Web Development (Django, Flask)
- Data Science & Machine Learning (Pandas, NumPy, TensorFlow)
- Automation and Scripting
- Software Testing
- Game Development
1
2. Downloading and installing Python
To write and execute Python code, you need to install the Python interpreter.
1. Visit the official website: [Link]/downloads.
2. Download the latest version for your operating system (Windows, macOS, or Linux).
3. Run the installer. IMPORTANT: Check the box that says 'Add Python to PATH' before clicking 'Install
Now'. This ensures you can run Python from your command line.
3. Introduction to IDLE and Python shell
IDLE (Integrated Development and Learning Environment) is Python’s built-in IDE.
- Python Shell: Interactive mode where you type a command and get immediate output (the REPL - Read,
Evaluate, Print, Loop). Great for testing small snippets.
- Script Mode: You write code in a file (ending in .py) and execute the entire file at once. Use 'File > New
File' in IDLE to open the script editor.
4. Running your first Python program
Open IDLE, open a new file, and type the following code:
print("Hello, World!")
Save the file as [Link] and press F5 (or Run > Run Module). The output will appear in the Python Shell.
Practical Classwork: Running Your First Python Program
Type these into their Python IDE or text editor and run them to understand the fundamental mechanics
of executing Python scripts.
Example 1: The Classic 'Hello, World!'
Objective: To demonstrate the most basic output functionality in Python.
Instructions: Type this exactly as shown and run it. Watch the console for the output.
print("Hello, World!")
print("I am running my first Python program.")
After running the code, write your result here:
Example 2: Interactive Greeting (Input and Output)
Objective: To introduce variables and user interaction using the input() function.
Instructions: Run the script, type your name into the console when prompted, and press Enter.
name = input("What is your name? ")
print("Welcome to Python programming, " + name + "!")
After running the code, write your result here:
2
Example 3: Basic Arithmetic
Objective: To show how Python handles numbers, variable assignment, and simple math.
Instructions: Change the numbers assigned to num1 and num2, then run it again to see the updated
result.
num1 = 15
num2 = 25
total = num1 + num2
print("The sum of", num1, "and", num2, "is:", total)
After running the code, write your result here:
Example 4: Simple Decision Making
Objective: To introduce basic control flow (if/else statements).
Instructions: Run the code. Then, change the 'weather' variable to "sunny" and run it again to see the
alternate output.
weather = "raining"
if weather == "raining":
print("Remember to bring an umbrella!")
else:
print("Have a great day!")
After running the code, write your result here:
Example 5: A Simple Counting Loop
Objective: To demonstrate how loops allow you to repeat actions easily.
Instructions: Watch how Python automatically prints multiple lines from a single block of code.
print("Counting from 1 to 5:")
for i in range(1, 6):
print("Count:", i)
After running the code, write your result here:
Module 2: Core Fundamentals
5. Basic Programming Concepts
Programming involves writing a set of instructions for a computer to execute. Key concepts include:
- Syntax: The grammatical rules of the language.
3
- Indentation: Python uses whitespace (indentation) to define blocks of code, unlike other languages
that use curly braces {}.
- Comments: Used to explain code. Prefix with # for single-line comments.
6. Data types: integers, floats, strings, and Booleans
Data types specify the kind of value a variable holds.
- Integers (int): Whole numbers (e.g., 10, -5).
- Floats (float): Decimal numbers (e.g., 3.14, -0.001).
- Strings (str): Text enclosed in quotes (e.g., "Hello", 'Python').
- Booleans (bool): Represents Truth values, either True or False.
Practical Classwork: Data Types (Integers, Floats, Strings, Booleans)
Example 1: Identifying Data Types using type()
Objective: To show students how Python natively categorizes different kinds of data.
Instructions: Run this code to see the underlying class/type of each variable.
age = 25
price = 19.99
name = "Alice"
is_student = True
print(type(age)) # Output: <class 'int'>
print(type(price)) # Output: <class 'float'>
print(type(name)) # Output: <class 'str'>
print(type(is_student)) # Output: <class 'bool'>
After running the code, write your result here:
Example 2: Working with Strings (Concatenation and Repetition)
Objective: To demonstrate how text data can be joined together or repeated.
Instructions: Change the 'name' variable to your own name and run the code.
greeting = "Hello"
name = "John"
# Concatenation (joining strings together)
full_greeting = greeting + ", " + name + "!"
print(full_greeting)
# Repetition (repeating a string multiple times)
cheer = "Hip Hip Hooray!\n" * 3
print(cheer)
4
After running the code, write your result here:
Example 3: Integer and Float Arithmetic
Objective: To show how whole numbers (integers) and decimal numbers (floats) interact.
Instructions: Notice how multiplying an integer by a float automatically results in a float.
quantity = 5 # Integer
unit_price = 4.50 # Float
total_cost = quantity * unit_price
print("Total cost: $", total_cost)
print("Data type of total_cost:", type(total_cost))
After running the code, write your result here:
Example 4: Boolean Logic and Comparisons
Objective: To illustrate how Booleans (True/False) represent logic, often resulting from comparisons.
Instructions: Change the 'score' variable to 50 and run the program again to see the Boolean change to
False.
score = 85
passing_score = 60
# Comparing two numbers results in a Boolean
has_passed = score >= passing_score
print("Did the student pass?", has_passed)
# Using a boolean directly to store a state
needs_extra_help = False
print("Needs tutoring?", needs_extra_help)
After running the code, write your result here:
5
Example 5: Type Casting (Converting Data Types)
Objective: To teach students how to convert one data type into another, which is crucial for handling
user input.
Instructions: Observe how the string "100" must be converted to an integer before we can do math with
it.
string_num = "100"
# Convert string to integer
actual_num = int(string_num)
result = actual_num + 50
print("Result after integer conversion:", result)
# Convert integer to float
float_num = float(actual_num)
print("Float representation:", float_num)
# Convert number back to string to concatenate with text
message = "The final score is " + str(result)
print(message)
After running the code, write your result here:
7. Variables and naming conventions
Variables are containers for storing data values. Python has no command for declaring a variable; it is
created the moment you first assign a value to it.
Naming Conventions:
- Must start with a letter or underscore (e.g., my_var, _name).
- Cannot start with a number.
- Case-sensitive (Age and age are different).
- Convention is to use 'snake_case' for variables (e.g., student_age = 20).
Practical Classwork: Variables and Naming Conventions
Example 1: Variable Creation and Dynamic Typing
Objective: To show how variables are created and how their values (and data types) can change over
time.
Instructions: Run this code to see how the 'user_status' variable changes from a string to a boolean.
# Creating initial variables
player_name = "Hero123"
score = 0
print("Player:", player_name, "| Score:", score)
# Updating the variable
6
score = score + 50
print("New Score:", score)
# Dynamic typing: changing the type of data a variable holds
user_status = "Active" # currently a string
print("Status:", user_status)
user_status = True # now a boolean
print("Is Active?:", user_status)
After running the code, write your result here:
Example 2: Valid vs. Invalid Variable Names
Objective: To demonstrate the strict rules Python enforces for naming variables.
Instructions: The invalid names are commented out so the code runs. Try uncommenting '1st_place =
"John"' to see the syntax error Python gives.
# VALID variable names
age = 14
user_age = 15
_user_age = 16
userAge2 = 17
print("All valid variables created successfully!")
# INVALID variable names (Uncomment to see the errors)
# 1st_place = "John" # Cannot start with a number
# first-name = "Alice" # Cannot contain hyphens
# my age = 20 # Cannot contain spaces
# class = "Math" # Cannot use Python keywords
After running the code, write your result here:
Example 3: Python Naming Conventions (snake_case)
Objective: To introduce 'snake_case', the standard naming convention in the Python community.
Instructions: Notice how underscores make multiple words readable without using spaces.
# Python standard: snake_case (all lowercase, words separated by
underscores)
first_name = "Sarah"
last_name = "Connor"
account_balance = 250.50
maximum_health_points = 100
# Other conventions (used in other languages or specific Python
contexts)
7
# camelCase
firstName = "John"
# PascalCase
FirstName = "Mike"
print("Welcome, ", first_name, last_name)
After running the code, write your result here:
Example 4: Assigning Multiple Variables at Once
Objective: To teach a Python shortcut for assigning values to multiple variables on a single line.
Instructions: Run the code, then change the values assigned to x, y, and z.
# Assigning multiple values to multiple variables
x, y, z = 10, 20, 30
print("x:", x)
print("y:", y)
print("z:", z)
# Assigning the same value to multiple variables
score1 = score2 = score3 = 100
print("All scores are initialized to:", score1)
After running the code, write your result here:
Example 5: Constants (By Convention)
Objective: To explain how Python developers indicate a variable should NOT be changed (a Constant).
Instructions: Observe the use of ALL_CAPS. Remember, Python won't actually stop you from changing it,
but it's a rule developers agree to follow.
# Constants are written in ALL CAPS to tell other programmers 'do
not change this'
PI = 3.14159
MAX_USERS = 50
WELCOME_MESSAGE = "Welcome to the system!"
radius = 5
area = PI * (radius ** 2)
print(WELCOME_MESSAGE)
print("The area of the circle is:", area)
8
# Note: You *can* technically change PI, but you shouldn't!
# PI = 4.0 # Bad practice!
After running the code, write your result here:
8. Basic arithmetic operations
Python supports standard arithmetic operators:
- Addition (+)
- Subtraction (-)
- Multiplication (*)
- Division (/) - Returns a float.
- Floor Division (//) - Rounds down to the nearest whole number.
- Modulus (%) - Returns the remainder of division.
- Exponentiation (**) - Power operation.
Practical Classwork: Basic Arithmetic Operations in Python
Example 1: The Standard Operators (+, -, *, /)
Objective: To practice basic addition, subtraction, multiplication, and division.
Instructions: Run this code to see how Python handles basic math. Notice that standard division (/)
always results in a float.
a = 15
b = 4
print("Addition: 15 + 4 =", a + b)
print("Subtraction: 15 - 4 =", a - b)
print("Multiplication: 15 * 4 =", a * b)
print("Division: 15 / 4 =", a / b)
After running the code, write your result here:
Example 2: Floor Division (//) and Modulus (%)
Objective: To understand specialized division operators used frequently in programming.
Instructions: Floor division drops the decimal, giving you a whole number. Modulus gives you ONLY the
remainder. Run the code to see this in action.
total_slices = 17
people = 5
# How many whole slices does each person get?
slices_per_person = total_slices // people
print("Slices per person:", slices_per_person)
9
# How many slices are left over?
leftover_slices = total_slices % people
print("Leftover slices:", leftover_slices)
After running the code, write your result here:
Example 3: Exponentiation (Powers)
Objective: To learn how to calculate powers (e.g., squaring or cubing a number) using the ** operator.
Instructions: Run the code. Try changing the exponent to 3 to calculate a cube.
base = 5
exponent = 2
# Calculating 5 squared (5 to the power of 2)
result = base ** exponent
print(base, "to the power of", exponent, "is:", result)
# Practical use: Area of a square
side_length = 7
area = side_length ** 2
print("Area of a 7x7 square:", area)
After running the code, write your result here:
Example 4: Order of Operations (PEMDAS)
Objective: To demonstrate that Python follows standard mathematical order of operations, and how to
use parentheses to change it.
Instructions: Notice how the two calculations yield completely different results despite having the same
numbers.
# Multiplication happens before addition
calc1 = 10 + 5 * 2
print("10 + 5 * 2 =", calc1) # Output will be 20
# Parentheses force addition to happen first
calc2 = (10 + 5) * 2
print("(10 + 5) * 2 =", calc2) # Output will be 30
After running the code, write your result here:
10
Example 5: Augmented Assignment Operators (+=, -=, *=)
Objective: To teach the shortcut for updating a variable based on its current value.
Instructions: These operators are very common in games (e.g., adding to a score) or loops (e.g.,
counting).
score = 50
print("Starting score:", score)
# Instead of: score = score + 10
score += 10
print("After gaining 10 points:", score)
# Instead of: score = score - 5
score -= 5
print("After a 5 point penalty:", score)
# Instead of: score = score * 2
score *= 2
print("After double points bonus:", score)
After running the code, write your result here:
9. Introduction to input and output
Output is handled by the print() function. Input is captured using the input() function.
Example:
name = input("Enter your name: ")
print("Hello", name)
Note: input() always returns a string. If you need a number, you must convert it (e.g., int(input("Age: "))).
Practical Classwork: Introduction to Input and Output
Example 1: Mastering the print() Function
Objective: To explore different ways to display text, including combining multiple items and customizing
the separator.
Instructions: Run the code and observe how commas automatically add spaces, and how 'sep' changes
that behavior.
# Basic printing
print("Welcome to Python class!")
# Printing multiple items (automatically separated by spaces)
print("The winning numbers are:", 7, 14, 21)
# Using a custom separator (sep)
11
print("Ready", "Set", "Go!", sep="...")
# Using end to prevent moving to a new line
print("Loading", end=" ")
print("Complete!")
After running the code, write your result here:
Example 2: Gathering String Input
Objective: To learn how to ask the user a question and store their text answer in a variable.
Instructions: Run the script, click into the console, type your favorite food, and press Enter.
# Asking for input
food = input("What is your favorite food? ")
# Responding using the stored variable
print("Wow, I love", food, "too!")
After running the code, write your result here:
Example 3: Gathering Numeric Input (Type Casting)
Objective: To demonstrate that input() always returns a string, so we must convert it if we want to do
math.
Instructions: Try removing the 'int()' function and see what happens when you run it (you will get an
error!).
# input() gives us a string, so we wrap it in int() to make it a
number
age = int(input("How old are you? "))
# Now we can safely do math
next_year_age = age + 1
print("On your next birthday, you will be", next_year_age)
After running the code, write your result here:
Example 4: Formatted Strings (f-strings)
Objective: To introduce f-strings, the most modern and readable way to mix text and variables in Python.
Instructions: Notice the 'f' before the opening quote, and how variables are placed directly inside curly
braces {}.
12
player_name = input("Enter your character's name: ")
level = int(input("Enter your starting level: "))
# Using an f-string for clean formatting
welcome_message = f"Welcome to the game, {player_name}! You are
starting at level {level}."
print(welcome_message)
After running the code, write your result here:
Example 5: Mini-Project - Simple Mad Libs
Objective: To combine multiple inputs and formatted output into a fun, interactive program.
Instructions: Answer the prompts one by one to generate a funny customized story.
print("--- Welcome to Python Mad Libs ---")
animal = input("Name an animal: ")
verb = input("Name an action verb (past tense, e.g., jumped): ")
place = input("Name a place: ")
story = f"Yesterday, a wild {animal} {verb} all the way to the
{place}!"
print("\nHere is your story:")
print(story)
After running the code, write your result here:
Module 3: Control Flow
10 & 11. Conditional Statements (if, elif, else)
Conditional statements allow a program to execute different blocks of code based on certain conditions.
- if: Tests the first condition.
- elif (else if): Tests subsequent conditions if the previous ones were False.
- else: Executes if all preceding conditions are False.
Example:
x = 10
if x > 10:
print("Greater")
elif x == 10:
print("Equal")
13
else:
print("Lesser")
Practical Classwork: Conditional Statements (if, elif, else)
Example 1: The Basic 'if' Statement (Single Condition)
Objective: To introduce the simplest form of decision making. The code inside the 'if' block only runs if
the condition is True.
Instructions: Run the code. Then change the temperature to 15 and run it again to see that nothing
prints.
temperature = 30
print("Checking the weather...")
if temperature >= 25:
print("It is a hot day!")
print("Don't forget to stay hydrated.")
print("Weather check complete.")
After running the code, write your result here:
Example 2: The 'if-else' Statement (Two Possible Paths)
Objective: To provide an alternative action when the 'if' condition is False.
Instructions: Enter a password. If it matches the secret, access is granted; otherwise, it is denied.
correct_password = "python123"
user_attempt = input("Enter the secret password: ")
if user_attempt == correct_password:
print("Access Granted! Welcome to the secret vault.")
else:
print("Access Denied! Incorrect password.")
After running the code, write your result here:
Example 3: The 'if-elif-else' Chain (Multiple Conditions)
Objective: To check multiple distinct conditions in sequence. As soon as one is True, the rest are skipped.
Instructions: Run the program and type different colors (red, yellow, green) to see the different outputs.
light_color = input("What color is the traffic light?
(red/yellow/green): ").lower()
if light_color == "red":
14
print("STOP!")
elif light_color == "yellow":
print("SLOW DOWN!")
elif light_color == "green":
print("GO!")
else:
print("Invalid color. Proceed with extreme caution!")
After running the code, write your result here:
Example 4: Categorizing Numbers
Objective: To use conditionals to evaluate numeric properties.
Instructions: Run the script multiple times with a positive number, a negative number, and a zero.
number = float(input("Enter a number: "))
if number > 0:
print("That is a POSITIVE number.")
elif number < 0:
print("That is a NEGATIVE number.")
else:
print("That number is EXACTLY ZERO.")
After running the code, write your result here:
Example 5: Mini-Project - The Grading System
Objective: To apply an if-elif-else chain to a real-world scenario where order matters.
Instructions: Note how the program checks the highest score first and works its way down. Enter
different scores to test it.
score = int(input("Enter the student's test score (0-100): "))
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"A score of {score} earns a grade of: {grade}")
15
After running the code, write your result here:
12. Comparison operators
Used to compare two values, resulting in a Boolean (True/False).
- Equal: ==
- Not equal: !=
- Greater than: >
- Less than: <
- Greater than or equal to: >=
- Less than or equal to: <=
Practical Classwork: Comparison Operators
Example 1: Equality (==) and Inequality (!=)
Objective: To understand how to test if two values are exactly the same, or if they are different.
Instructions: Run the code. Try changing 'entered_pin' to 1234 to see the inequality condition clear.
correct_pin = 1234
entered_pin = 9999
# Checking for equality (==)
is_match = (entered_pin == correct_pin)
print("Is the PIN correct?", is_match)
# Checking for inequality (!=)
if entered_pin != correct_pin:
print("Warning: The entered PIN does not match our records!")
After running the code, write your result here:
Example 2: Strict Inequalities (Greater Than '>' and Less Than '<')
Objective: To explore numeric thresholds where the boundary number itself is not included.
Instructions: Run the code. Notice what happens if you change 'child_height' to exactly 120. (It will print
False because it must be strictly greater than 120).
minimum_height = 120 # in cm
child_height = 115
# Strictly greater than
can_ride = child_height > minimum_height
print(f"Height {child_height}cm > {minimum_height}cm:", can_ride)
# Strictly less than
max_temperature = 0 # Freezing point
current_temp = -3
is_freezing = current_temp < max_temperature
16
print(f"Is the current temperature ({current_temp}°C) freezing?",
is_freezing)
After running the code, write your result here:
Example 3: Non-Strict Inequalities (>= and <=)
Objective: To handle boundaries where the target number is included in the condition.
Instructions: Change the age to 18. Notice that 'age >= 18' becomes True, because 18 is equal to 18.
voting_age = 18
user_age = 18
# Greater than or equal to
is_eligible_to_vote = user_age >= voting_age
print(f"Age {user_age} is eligible to vote:", is_eligible_to_vote)
# Less than or equal to
max_capacity = 50
current_guests = 50
# Is the venue safe? (Guests must be less than or equal to
capacity)
is_safe = current_guests <= max_capacity
print("Is the venue within capacity limits?", is_safe)
After running the code, write your result here:
Example 4: Comparing Text (String Comparisons)
Objective: To demonstrate that comparison operators also work on text data, following alphabetical
order and case sensitivity.
Instructions: Run this code to see how Python evaluates strings alphabetically. Note that uppercase
letters have lower ASCII values than lowercase letters!
word1 = "apple"
word2 = "banana"
# Alphabetical comparison (comes earlier in the alphabet means
'less than')
print(f"Does '{word1}' come before '{word2}' alphabetically?",
word1 < word2)
# Case sensitivity in comparisons
print("Is 'Python' equal to 'python'?", "Python" == "python")
print("Is 'Python' not equal to 'python'?", "Python" != "python")
After running the code, write your result here:
17
Example 5: Evaluating Comparisons inside Print Statements
Objective: To show students that a comparison expression resolves directly to True or False without
needing an 'if' statement.
Instructions: Observe how we can print the direct truth value of math statements.
x = 10
y = 20
print("--- Quick Math Logic Checks ---")
print("Is x equal to y?", x == y)
print("Is x less than y?", x < y)
print("Is x multiplied by 2 equal to y?", x * 2 == y)
print("Is y divided by 2 not equal to x?", y / 2 != x)
After running the code, write your result here:
13. Logical operators (and, or, not)
Used to combine conditional statements.
- and: Returns True if BOTH statements are true.
- or: Returns True if ONE of the statements is true.
- not: Reverses the result, returns False if the result is true.
Practical Classwork: Logical Operators (and, or, not)
Example 1: The 'and' Operator (Both Conditions Must Be True)
Objective: To demonstrate how the 'and' operator requires every single condition to evaluate to True for
the overall block to execute.
Instructions: Run the code. Try changing 'gpa' to 3.2 and observe that the scholarship requirement is no
longer met.
gpa = 3.8
attendance_rate = 95 # in percent
# Both conditions must be True to qualify
if gpa >= 3.5 and attendance_rate >= 90:
print("Congratulations! You qualify for the academic
scholarship.")
else:
print("Sorry, you do not meet all the requirements for the
scholarship.")
After running the code, write your result here:
18
Example 2: The 'or' Operator (At Least One Condition Must Be True)
Objective: To show how the 'or' operator triggers an action if any individual condition evaluates to True.
Instructions: Run the script. Try changing 'is_weekend' to False but 'is_holiday' to True. Notice how the
code block still executes.
is_weekend = True
is_holiday = False
# Only one condition needs to be True to sleep in
if is_weekend or is_holiday:
print("You can sleep in today! No alarm needed.")
else:
print("Wake up! It is a regular working day.")
After running the code, write your result here:
Example 3: The 'not' Operator (Reversing Truth Values)
Objective: To understand how the 'not' operator flips a boolean value (True becomes False, and vice
versa).
Instructions: This is highly useful for checking if something is 'not' the case, such as checking if a system
is offline.
is_game_over = False
# 'not False' evaluates to True
if not is_game_over:
print("The game is still running! Keep playing.")
else:
print("Game Over. Please restart.")
After running the code, write your result here:
Example 4: Combining Operators with Parentheses (Precedence)
Objective: To teach students how to combine 'and' & 'or' operators using parentheses to clearly define
the order of logical evaluation.
Instructions: Run the code with different combinations of ages and adult accompaniment to see who is
allowed to watch the movie.
age = 14
is_accompanied_by_adult = True
# A user can watch the movie if they are 18 OR (at least 13 AND
with an adult)
if age >= 18 or (age >= 13 and is_accompanied_by_adult):
19
print("Access granted. Enjoy the movie!")
else:
print("Access denied. This movie is rated PG-13.")
After running the code, write your result here:
Example 5: Mini-Project - Secure Portal Authentication
Objective: To build a comprehensive conditional statement utilizing 'and' alongside 'not' for a secure
entry system.
Instructions: Test this code by changing the credentials or the lockout status to see how multiple logic
gates keep an account secure.
stored_username = "admin"
stored_password = "secret123"
input_user = input("Enter username: ")
input_pass = input("Enter password: ")
is_account_locked = False
# User must match both credentials AND the account must NOT be
locked
if input_user == stored_username and input_pass ==
stored_password and not is_account_locked:
print("Login successful! Welcome to your dashboard.")
elif is_account_locked:
print("Login failed: This account is locked. Contact
support.")
else:
print("Login failed: Invalid username or password.")
After running the code, write your result here:
14. Nested if statements
You can have if statements inside other if statements. This is called nesting.
Example:
x = 41
if x > 10:
print("Above ten,")
if x > 20:
print("and also above 20!")
else:
print("but not above 20.")
20
Practical Classwork: Nested if Statements
Example 1: Number Property Classifier (Positive -> Even/Odd)
Objective: To introduce the concept of placing an if-else block inside another if block.
Instructions: Observe how the program checks if a number is positive first. Only if it is positive does it
then check if it is even or odd.
number = int(input("Enter an integer: "))
if number >= 0:
print("The number is POSITIVE (or zero).")
# Secondary nested check
if number % 2 == 0:
print("Specifically, it is an EVEN number.")
else:
print("Specifically, it is an ODD number.")
else:
print("The number is NEGATIVE.")
After running the code, write your result here:
Example 2: ATM Cash Withdrawal Security
Objective: To model a real-world multi-step verification process.
Instructions: Run the code. See how an incorrect PIN prevents the balance check from running entirely.
correct_pin = 1234
account_balance = 500
entered_pin = int(input("Enter your 4-digit ATM PIN: "))
if entered_pin == correct_pin:
print("PIN Verified successfully.")
amount_to_withdraw = int(input("Enter withdrawal amount: $"))
# Nested condition to verify funds
if amount_to_withdraw <= account_balance:
account_balance -= amount_to_withdraw
print(f"Success! Please take your cash. Remaining balance:
${account_balance}")
else:
print("Transaction Denied: Insufficient funds!")
else:
print("Card Blocked: Invalid PIN entry.")
After running the code, write your result here:
21
Example 3: Dynamic E-Commerce Shipping Costs
Objective: To use nesting to handle grouped tiers (e.g., different rules for Domestic vs International
shipping).
Instructions: Try changing the destination and order totals to see how nested thresholds calculate
varying shipping fees.
destination = input("Enter shipping region (domestic /
international): ").lower()
order_total = float(input("Enter total order value: $"))
if destination == "domestic":
# Nested threshold check for domestic orders
if order_total >= 50.0:
shipping = 0.0
else:
shipping = 5.99
elif destination == "international":
# Nested threshold check for international orders
if order_total >= 150.0:
shipping = 10.00
else:
shipping = 25.00
else:
shipping = -1
if shipping == 0.0:
print("You qualify for Free Shipping!")
elif shipping > 0:
print(f"Shipping fee applied: ${shipping:.2f}")
else:
print("Unknown shipping destination error.")
After running the code, write your result here:
Example 4: Movie Theater Pricing Matrix
Objective: To evaluate age tiers first, and then check loyalty standing to alter specific pricing structures.
Instructions: Notice how the inner loyalty checks are completely unique depending on whether the user
is an adult or a child.
age = int(input("Enter the moviegoer's age: "))
is_member = input("Is the guest a VIP Loyalty Member? (yes/no):
").lower() == "yes"
if age >= 18:
22
print("Standard Adult Admission")
if is_member:
print("Ticket Price: $10.00 (VIP Discount Applied)")
else:
print("Ticket Price: $14.00")
else:
print("Child/Teen Admission")
if is_member:
print("Ticket Price: $5.00 (VIP Discount Applied)")
else:
print("Ticket Price: $8.00")
After running the code, write your result here:
Example 5: Mini-Project - Multi-User Secure Portal Roles
Objective: To combine nested checks to perform both identity authentication and permission mapping.
Instructions: Run the code. Test passing correct usernames with incorrect passwords, or using an
unknown user.
print("--- Portal Login Verification ---")
user = input("Username: ")
password = input("Password: ")
if user == "admin":
if password == "adminpass":
print("Access Granted! Level: System Administrator (Full
Read/Write)")
else:
print("Access Denied: Invalid password for user 'admin'.")
elif user == "staff":
if password == "staffpass":
print("Access Granted! Level: Standard Employee (Read-
Only Records)")
else:
print("Access Denied: Invalid password for user 'staff'.")
else:
print("Access Denied: Username not found in the directory.")
After running the code, write your result here:
23
Module 4: Iteration and Loops
15 & 16. Introduction to loops (for and while)
Loops are used to iterate over a sequence or repeat a block of code.
- while loop: Executes a block of code as long as a specified condition is true. Watch out for infinite loops!
- for loop: Used for iterating over a sequence (like a list, string, or range).
After running the code, write your result here:
Practical Classwork: Introduction to Loops (for and while)
Example 1: The Basic 'while' Loop (Condition-Controlled)
Objective: To demonstrate how a while loop repeats an action as long as a specified condition remains
True.
Instructions: Run the code and watch it count. Note the importance of the 'count += 1' line—ask
students what would happen if that line were missing (an infinite loop!).
count = 1
# The loop will run as long as count is less than or equal to 5
while count <= 5:
print(f"Loop iteration number: {count}")
count += 1 # Increment the counter to eventually end the
loop
print("The while loop has ended.")
After running the code, write your result here:
Example 2: The Basic 'for' Loop with range() (Count-Controlled)
Objective: To introduce the for loop and the range() function for executing code a fixed number of times.
Instructions: Observe how the loop automatically increments the variable 'i'. Remind students that
range(1, 6) starts at 1 but stops *before* 6.
print("Starting the for loop:")
# range(1, 6) generates numbers from 1 up to (but not including)
6
for i in range(1, 6):
print(f"Current count is: {i}")
print("The for loop has ended.")
After running the code, write your result here:
24
Example 3: Iterating Over a Sequence (Strings)
Objective: To show how a for loop can automatically step through each character in a sequence, like a
text string.
Instructions: Change the 'word' variable to a different string (like your name) and watch how the loop
adapts.
word = "PYTHON"
print(f"Spelling out the word '{word}':")
# The loop variable 'letter' takes on the value of each character
one by one
for letter in word:
print("Letter:", letter)
print("Spelling complete!")
After running the code, write your result here:
Example 4: The Accumulator Pattern (Calculating a Sum)
Objective: To teach a common programming pattern where a variable accumulates values inside a loop.
Instructions: Run this program to compute the sum of all numbers from 1 to 10. Students can modify the
range limit to sum up to 100.
total_sum = 0
# Loop through numbers 1 to 10
for num in range(1, 11):
total_sum += num # Add the current number to our running
total
print(f"Added {num}, current running total is: {total_sum}")
print(f"\nThe final sum of numbers from 1 to 10 is: {total_sum}")
After running the code, write your result here:
Example 5: Mini-Project - Interactive Sentinel Loop
Objective: To implement a while loop that controls a program interactively based on dynamic user input
rather than a fixed counter.
Instructions: Run the code. Type random words to see it repeat. Type 'exit' exactly to make the loop stop.
print("--- Welcome to the Echo Chamber ---")
print("(Type 'exit' to stop the program)\n")
25
user_input = ""
# The loop continues until the user types 'exit'
while user_input.lower() != "exit":
user_input = input("Type something: ")
# Only echo back if they didn't choose to exit
if user_input.lower() != "exit":
print(f"Echo: {user_input}\n")
print("Loop broken successfully. Goodbye!")
After running the code, write your result here:
17. Range and enumerate functions
- range(start, stop, step): Generates a sequence of numbers. range(5) generates 0, 1, 2, 3, 4.
- enumerate(iterable): Adds a counter to an iterable and returns it. Useful when you need both the
index and the value in a loop.
Example:
for index, value in enumerate(['a', 'b', 'c']):
print(index, value)
Practical Classwork: Range and Enumerate Functions
Example 1: The Three Flavors of range()
Objective: To teach students how range() can accept one, two, or three arguments to control the start,
stop, and step of a loop.
Instructions: Run the code. Notice how range(stop) defaults to starting at 0, and how the step argument
acts as a skip count.
# 1. range(stop) - runs from 0 up to (but excluding) 5
print("range(5):")
for i in range(5):
print(i, end=" ")
print("\n")
# 2. range(start, stop) - runs from 2 up to (but excluding) 7
print("range(2, 7):")
for i in range(2, 7):
print(i, end=" ")
print("\n")
# 3. range(start, stop, step) - skips by 2s from 1 up to (but
excluding) 10
print("range(1, 10, 2):")
26
for i in range(1, 10, 2):
print(i, end=" ")
After running the code, write your result here:
Example 2: Counting Backwards with range()
Objective: To demonstrate how to use a negative step value in range() to iterate in reverse order.
Instructions: Run the script to simulate a rocket countdown. Note that the stop boundary must be lower
than the start boundary when using a negative step.
import time
print("Rocket Launch Countdown!")
# range(start, stop, step) -> counts down from 10 to 1
for countdown in range(10, 0, -1):
print(countdown)
[Link](0.5) # Pause for half a second for dramatic
effect
print("BLAST OFF! �")
After running the code, write your result here:
Example 3: Introduction to enumerate()
Objective: To demonstrate how enumerate() solves the common problem of needing both the item and
its index position inside a loop.
Instructions: Observe how enumerate() automatically unzips into two variables: 'index' (the counter)
and 'task' (the item).
todo_list = ["Clean room", "Study Python", "Buy groceries",
"Exercise"]
print("Your Daily Tasks:")
# enumerate gives you both the position index and the item value
for index, task in enumerate(todo_list):
print(f"Task Index: {index} | Task Name: {task}")
After running the code, write your result here:
27
Example 4: Customizing the Start Index in enumerate()
Objective: To show how to use the optional 'start' argument in enumerate() to display human-readable
numbering (starting at 1 instead of 0).
Instructions: Run the script. Notice how the underlying list index is shifted to start from 1 for clean
presentation, while the list itself remains unchanged.
fruits = ["Apple", "Banana", "Cherry", "Date"]
print("Available Fruit Options:")
# Setting start=1 tells Python to begin numbering the index at 1
for number, fruit in enumerate(fruits, start=1):
print(f"{number}. {fruit}")
After running the code, write your result here:
Example 5: Mini-Project - Student Attendance Tally
Objective: To build a practical scenario that combines structural data arrays with enumerate() to format
an active tracking system.
Instructions: Run the program. This script showcases how to print out an ordered list of students
alongside their entry arrival position.
print("--- Classroom Arrival Tracker ---")
students_arrived = ["Alice", "Bob", "Charlie", "David", "Eva"]
print("Order of Arrival Today:")
for position, student in enumerate(students_arrived, start=1):
# Using f-strings to display the position and name clearly
print(f"Position #{position}: {student} has entered the
room.")
print(f"\nTotal students present: {len(students_arrived)}")
After running the code, write your result here:
18. Loop control statements (break and continue)
- break: Instantly exits the loop completely, regardless of the condition.
- continue: Skips the current iteration of the loop and moves immediately to the next iteration.
28
Practical Classwork: Loop Control Statements (break and continue)
Example 1: The 'break' Statement (Early Exit)
Objective: To demonstrate how a break statement immediately halts a loop, skipping any remaining
iterations.
Instructions: Run the code. Notice how the loop stops printing numbers as soon as it hits 5, even though
the range goes up to 10.
print("Starting loop with range(1, 11):")
for number in range(1, 11):
if number == 5:
print("-> Found 5! Breaking out of the loop early.")
break # Exits the loop entirely
print("Current number:", number)
print("Loop has been terminated.")
After running the code, write your result here:
Example 2: The 'continue' Statement (Skip and Move On)
Objective: To show how continue skips only the current iteration, allowing the loop to keep running for
the subsequent items.
Instructions: Run the script. Notice that the number 3 is completely missing from the output, but the
loop finishes counting to 5.
print("Counting from 1 to 5, skipping 3:")
for i in range(1, 6):
if i == 3:
print("-> Skipping 3 using 'continue'")
continue # Jumps straight to the next iteration
print("Number:", i)
print("Loop completed successfully.")
After running the code, write your result here:
Example 3: 'break' in an Infinite 'while True' Loop
Objective: To create a loop that runs indefinitely until a specific user action occurs, which is a common
pattern for menus.
Instructions: Enter different inputs. The loop will keep asking for a password until you type 'secret'.
29
while True:
password = input("Enter the secret password to stop this loop:
")
if password == "secret":
print("Correct password! Breaking the loop...")
break
print("Incorrect. The loop continues running.\n")
print("Successfully escaped the infinite loop!")
After running the code, write your result here:
Example 4: Skipping Items with 'continue' (Vowel Remover)
Objective: To use continue in a data filtering context by skipping specified elements during text
processing.
Instructions: Change the sentence to see how the loop strips out all instances of the letter 'e' and 'o'
while printing everything else.
text = "hello everyone"
print(f"Original text: {text}")
print("Filtered output (without 'e' or 'o'): ", end="")
for letter in text:
if letter == 'e' or letter == 'o':
continue # Skip these characters and go to the next
letter
print(letter, end="")
print() # Final new line
After running the code, write your result here:
Example 5: Mini-Project - Smart Shopping Cart Scanner
Objective: To combine both break and continue in a single practical workflow simulation.
Instructions: Run the code. Observe how an out-of-stock item is skipped with continue, while a
suspicious item triggers a security break that drops the whole checkout process.
items_to_scan = ["apple", "banana", "OUT_OF_STOCK", "milk",
"SUSPICION_FLAG", "bread"]
print("--- Starting Cashier Checkout Scanner ---")
for item in items_to_scan:
if item == "OUT_OF_STOCK":
30
print("Skipping 'OUT_OF_STOCK' item... running continue.")
continue # Skips this item, continues scanning the next
if item == "SUSPICION_FLAG":
print("⚠ SECURITY ALARM TRIPPED! Freezing scanner and
running break!")
break # Halts the entire scanning process completely
print(f"Successfully scanned: {item}")
print("\nCheckout sequence finalized.")
After running the code, write your result here:
19. Nested loops
A nested loop is a loop inside a loop. The "inner loop" will be executed one time for each iteration of the
"outer loop".
Practical Classwork: Nested Loops
Example 1: The Coordinate Grid (Basic Mechanics)
Objective: To observe how the inner loop fully executes for each step of the outer loop.
Instructions: Run the code. Notice how the 'X' value stays the same while the 'Y' value runs through its
entire sequence.
# The outer loop controls rows (X coordinate)
for x in range(1, 4):
print(f"Outer loop starting: x = {x}")
# The inner loop controls columns (Y coordinate)
for y in range(1, 4):
print(f" Inner loop: (x={x}, y={y})")
print("Outer loop iteration ending.\n")
After running the code, write your result here:
Example 2: Creating a Multiplication Table
Objective: To use nested loops to generate grid-based mathematical data structures.
Instructions: Observe how the end=" " modifier prevents lines from breaking prematurely, and how an
empty print() creates a clean grid row by row.
print("--- Multiplication Table (1 to 5) ---")
31
# Outer loop handles the rows
for row in range(1, 6):
# Inner loop handles the columns within that row
for col in range(1, 6):
product = row * col
# using ':3' inside the f-string keeps the numbers
aligned nicely
print(f"{product:3}", end=" ")
print() # Moves to the next line when a full row is finished
After running the code, write your result here:
Example 3: Pattern Printing (Right-Angled Triangle)
Objective: To demonstrate how the inner loop can dynamically depend on the current state of the outer
loop variable.
Instructions: Look closely at the inner loop's range. It changes sizes dynamically based on the current
row number 'i'.
number_of_rows = 5
# Outer loop controls how many total rows to build
for i in range(1, number_of_rows + 1):
# Inner loop determines how many stars to print on the
current row
for j in range(i):
print("*", end=" ")
print() # Jump down to the next row line
After running the code, write your result here:
Example 4: Iterating Over Nested Data (List of Lists)
Objective: To process multi-dimensional data layouts, such as a school gradebook tracking individual
grades for multiple students.
Instructions: The outer loop grabs each individual student roster list, and the inner loop inspects the
elements hidden inside it.
# A 2D list matrix representing 3 students and their test scores
gradebook = [
[88, 92, 79], # Student 1
[95, 100, 91], # Student 2
[70, 65, 80] # Student 3
32
]
# Outer loop steps through each student array row
for student_index, scores in enumerate(gradebook, start=1):
print(f"Analyzing Student #{student_index}'s Scores:")
# Inner loop digs into the elements inside that specific row
array
for single_score in scores:
print(f" - Found Score: {single_score}")
print()
After running the code, write your result here:
Example 5: Mini-Project - Two-Dice Combination Finder
Objective: To construct a combination algorithm that tests every potential pair layout to solve a
conditional requirement.
Instructions: Run the code. This logic simulates rolling two distinct 6-sided dice to discover all exact
combination matches that sum to 7.
print("--- Target Score Dice Combination Finder ---")
target_sum = 7
print(f"Searching for roll variations that add up to:
{target_sum}\n")
# Outer loop represents the first die (faces 1-6)
for die1 in range(1, 7):
# Inner loop represents the second die (faces 1-6)
for die2 in range(1, 7):
# Check if the combined face values match our objective
target
if die1 + die2 == target_sum:
print(f"Match Confirmed! [Die #1: {die1}] + [Die #2:
{die2}] = {target_sum}")
After running the code, write your result here:
Module 5: Modularity
20. Introduction to functions and Function definition
A function is a block of organized, reusable code that runs only when it is called. You can pass data
(parameters) into a function, and it can return data as a result.
33
Function Definition uses the 'def' keyword.
Example:
def greet(name):
return "Hello, " + name
message = greet("Alice")
print(message)
Practical Classwork: Introduction to Functions and Function Definition
Example 1: Defining a Simple Function (No Parameters, No Return)
Objective: To introduce the absolute basics of creating a function using the 'def' keyword and executing
it by calling its name.
Instructions: Run the code. Notice how nothing happens until the function is explicitly 'called' at the
bottom.
# 1. Defining the function
def show_welcome_message():
print("===============================")
print("Welcome to the Python Portal!")
print("We hope you have a great day.")
print("===============================")
print("The program is starting...")
# 2. Calling the function (reusing it twice)
show_welcome_message()
print("Doing some other work here...")
show_welcome_message()
After running the code, write your result here:
Example 2: Functions with Parameters (Passing Inputs)
Objective: To show how functions can accept inputs (parameters) to produce dynamic results based on
the data provided.
Instructions: Run the script. Try calling 'greet_user' with your own name as an argument.
# 'name' is a parameter—a placeholder for data coming into the
function
def greet_user(name):
print(f"Hello, {name}! Welcome back to your dashboard.")
# Passing different pieces of text data (arguments) into the
function
34
greet_user("Alice")
greet_user("Bob")
greet_user("Charlie")
After running the code, write your result here:
Example 3: Returning Values from a Function (The 'return' Keyword)
Objective: To teach the difference between displaying data inside a function (print) and passing data
back to the main program (return).
Instructions: Emphasize to students that 'return' exits the function and passes the result back, allowing it
to be stored in a variable.
def calculate_square(number):
result = number * number
return result # Sends the calculated answer back to the line
that called it
# Call the function and save its returned answer into a variable
my_square = calculate_square(6)
print(f"The square of 6 is: {my_square}")
# You can also use the return value directly inside a print
statement
print(f"The square of 10 is: {calculate_square(10)}")
After running the code, write your result here:
Example 4: Default Parameter Values
Objective: To demonstrate how to make function arguments optional by assigning default values to
parameters in the definition.
Instructions: Observe what happens when you call 'introduce_pet' without providing a second argument.
# 'animal_type' has a default value of 'dog'
def introduce_pet(pet_name, animal_type="dog"):
print(f"I have a lovely {animal_type} named {pet_name}!")
# 1. Calling with both arguments (overrides the default)
introduce_pet("Whiskers", "cat")
# 2. Calling with only the required argument (falls back to the
default)
introduce_pet("Buddy")
introduce_pet("Max")
35
After running the code, write your result here:
Example 5: Mini-Project - Modular Geometric Calculator
Objective: To build an orderly, modular script featuring multiple custom function definitions that split a
math utility into clear responsibilities.
Instructions: Run the script and call different math operations. This mimics how large software
architecture is organized into separate functions.
def area_of_rectangle(width, height):
return width * height
\def perimeter_of_rectangle(width, height):
return 2 * (width + height)
# Main simulation block using our defined functions
w = 10
h = 5
# Fetch values back from our calculator modules
rect_area = area_of_rectangle(w, h)
rect_perim = perimeter_of_rectangle(w, h)
print(f"--- Rectangle Dimension Analyzer [{w}x{h}] ---")
print(f"Calculated Area: {rect_area} sq units")
print(f"Calculated Perimeter: {rect_perim} units")
After running the code, write your result here:
36
Practice Workbook
Test your knowledge by completing the following exercises. Each section corresponds to the modules
covered in the lesson notes.
Section 1: Basics & Variables
1. Write a script that assigns your favorite color to a variable and prints 'My favorite color is [color]'.
2. Swap the values of two variables (a = 5, b = 10) without typing the numbers 5 and 10 again.
3. Write a program that asks the user for the radius of a circle and prints its area (use 3.14 for pi).
Your Answer / Code Space:
Section 2: Control Flow
1. Write a program that takes an integer from the user and prints whether it is 'Even' or 'Odd'.
2. Create a grading program: ask for a score (0-100). Print A if >= 90, B if >= 80, C if >= 70, D if >= 60,
otherwise F.
3. Write a script that checks if a given year is a leap year (divisible by 4, but not 100 unless also divisible
by 400).
Your Answer / Code Space:
37
Section 3: Loops
1. Use a for loop to print all even numbers between 1 and 20.
2. Write a while loop that keeps asking the user 'Enter yes to stop' until they type exactly 'yes'.
3. Use nested loops to print a pyramid pattern of asterisks (*) with 5 rows.
Your Answer / Code Space:
Section 4: Functions
1. Define a function called 'is_prime(n)' that returns True if a number is prime and False otherwise.
2. Write a function 'max_of_three(a, b, c)' that returns the largest of three numbers without using the
built-in max() function.
3. Create a function 'reverse_string(text)' that takes a string and returns it reversed.
Your Answer / Code Space:
38