Learning Module in Python Programming
Learning Module in Python Programming
Welcome, aspiring Python programmers, to this comprehensive learning module on Programming with
Python. Prepare to embark on an engaging and rewarding journey that will build a strong foundation in
one of the most widely used and versatile programming languages in the world today. This course begins
with an introduction to Python’s background and development, emphasizing its philosophy of simplicity,
readability, and efficiency—qualities that have made Python a preferred language across many domains,
including software development, data science, artificial intelligence, cybersecurity, automation, and web
development.
This module is carefully designed to guide you step-by-step through the essential concepts of Python
programming. You will start by understanding Python’s origins and evolution, then proceed to master its
fundamental syntax and structure. As the course progresses, you will learn how to control program flow,
work with functions, handle data structures, and apply logical problem-solving techniques. Throughout
the course, strong emphasis is placed on practical application, enabling you to translate theoretical
knowledge into real working programs.
By the end of this course, you will have acquired the confidence and technical skills needed to design,
implement, and debug Python programs that solve real-world problems. Get ready to explore the core
concepts that have established Python as a leading language in today’s dynamic and fast-evolving
technology landscape.
This module provides a comprehensive introduction to Python programming and the fundamental
concepts required for building reliable and efficient software applications. It begins with an overview of
Python’s origins and evolution, tracing its development from its creation by Guido van Rossum to its
current status as one of the most influential and widely used programming languages in modern
computing. The discussion highlights Python’s design philosophy, emphasizing simplicity, readability, and
productivity, which have contributed significantly to its success in academic, scientific, and commercial
environments.
The module then examines the progression of Python versions and the important features introduced
over time, including enhanced syntax support, dynamic typing, list comprehensions, exception handling,
and powerful standard libraries that continue to expand Python’s capabilities. Emphasis is placed on
Python’s multi-paradigm nature, demonstrating how it supports procedural programming, functional
programming, and object-oriented programming, allowing developers to choose the most appropriate
approach for a given problem.
Next, the module transitions into the specifics of Python syntax, covering program structure, indentation
rules, data types, operators, and the execution model of Python programs. Students will learn how Python
code is interpreted and executed by the Python interpreter, as well as how scripts are developed, tested,
and debugged.
Furthermore, the module provides instruction on producing output using the print() function, the
importance of writing clear and meaningful comments for code readability, and the declaration and use
of variables with different data types. Overall, this module establishes a strong foundation in Python
programming by integrating its history, language features, execution process, and essential programming
constructs.
Course Outline for Programming with Python
This course introduces fundamental programming concepts using Python. Students develop problem -
solving skills through hands-on coding activities, real-world examples, and graded programming tasks.
Emphasis is placed on algorithmic thinking, structured programming, and data manipulation.
I. Midterm
Duration: 2 Weeks
Overview:
This chapter introduces Python as a programming language, including its history, features, development
environment, and basic program structure. Students write their first programs and understand how
Python executes instructions.
Learning Objectives:
Students will be able to:
Topics Covered:
Activities:
Duration: 2 Weeks
Overview:
This chapter covers Python expressions, variables, and data manipulation. Students learn to process
input, format output, and manage data types effectively.
Learning Objectives:
Students will be able to:
Topics Covered:
Activities:
Duration: 2 Weeks
Overview:
This chapter introduces program decision-making using conditional statements and logical operations.
Learning Objectives:
Students will be able to:
Boolean values
Comparison and logical operators
if, if-else, elif statements
Nested decisions
Conditional expressions
Activities:
Duration: 2 Weeks
Overview:
This chapter focuses on iterative programming using loops and control statements.
Learning Objectives:
Students will be able to:
Topics Covered:
While loop
For loop
Nested loops
Break and continue
For–else statement
Activities:
Duration: 2 Weeks
Overview:
Students learn how to build reusable and organized programs using functions.
Learning Objectives:
Students will be able to:
Topics Covered:
Defining functions
Function parameters and return values
Practical applications (ATM system, calculators, billing systems)
Activities:
Duration: 2 Weeks
Overview:
This chapter introduces Python’s modular system and external libraries.
Learning Objectives:
Students will be able to:
Activities:
Duration: 2 Weeks
Overview:
This chapter covers advanced text processing using Python string operations.
Learning Objectives:
Students will be able to:
Topics Covered:
Activities:
Duration: 2 Weeks
Overview:
Students explore Python’s core data structures for efficient data management.
Learning Objectives:
Students will be able to:
Topics Covered:
Activities:
Duration: 2 Weeks
Overview:
This final chapter integrates algorithmic problem solving with project development.
Learning Objectives:
Students will be able to:
Topics Covered:
Activities:
References
1. Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2022). Introduction to algorithms (4th
ed.). MIT Press.
2. Downey, A. B. (2016). Think Python: How to think like a computer scientist (2nd ed.). O’Reilly
Media. [Link]
3. Lutz, M. (2013). Learning Python (5th ed.). O’Reilly Media.
4. Miller, B. N., & Ranum, D. L. (2014). Problem solving with algorithms and data structures using
Python. Franklin, Beedle & Associates.
5. Python Software Foundation. (2024). Python documentation. [Link]
6. GeeksforGeeks. (n.d.). Data structures and algorithms in Python.
[Link]
7. Real Python. (n.d.). Python tutorials. [Link]
TABLE OF CONTENTS
TOPIC Page
TOPIC Page
This chapter introduces the fundamental concepts of Python programming, beginning with the background of
the language and its practical applications. It explains basic input and output operations, the use of variables,
and the fundamentals of working with strings and numbers. The chapter also discusses common error messages
and the importance of using comments to improve code readability and maintenance. Finally, it introduces
docstrings as a formal method of documenting Python programs for clarity and professionalism.
Background
Core Characteristics
Interpreted: Python code is executed line-by-line by an interpreter. This makes debugging easier and
development faster because there is no separate "compilation" step.
Dynamically Typed: You don't need to declare whether a variable is a number or a string. Python figures
it out at runtime ($x = 5$ is automatically an integer).
High-Level: It abstracts away complex details like memory management (handled by a "Garbage
Collector"), allowing you to focus on solving the problem rather than managing hardware.
Multi-paradigm: It supports various programming styles, including Object-Oriented (OOP), Procedural,
and Functional programming.
Key Features
1. Readability: Python’s syntax is remarkably close to the English language. This reduces the cost of
program maintenance and makes it the "go-to" language for beginners.
2. Extensive Standard Library: It comes with a "batteries-included" philosophy, offering built-in modules
for everything from web servers to file manipulation and cryptography.
3. Portability: Python is cross-platform; code written on Windows will generally run on macOS or Linux
without modification.
4. Free and Open Source: Managed by the Python Software Foundation (PSF), it is free to use and
distribute, even for commercial purposes.
Popular Use Cases: Python is versatile enough to be used in almost every technical field today:
Advantages
Productivity: You can achieve the same result with 5 lines of Python that might take 20 lines of C++ or
Java.
Community Support: Because it’s so popular, if you hit a bug, someone has likely already solved it on
Stack Overflow.
Integration: It can easily "glue" together components written in other languages (like C or C++).
1
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Disadvantages
Execution Speed: Being interpreted makes it slower than compiled languages like C.
Mobile Development: It is not natively supported for mobile apps (iOS/Android), though frameworks
like Kivy exist.
Global Interpreter Lock (GIL): A technical limitation that prevents Python from running multiple
threads of code simultaneously on multi-core processors, which can hinder performance in specific
high-load tasks.
Web Development Building the "back-end" (server-side) of websites. Django, Flask, FastAPI
Game
Prototyping and logic scripting for games. Pygame
Development
One reason why Python is popular is because many libraries exist for doing real
work. A library is a collection of code that can be used in other programs. Python
comes with an extensive Standard Library for solving everyday computing
problems like extracting data from files and creating summary reports. In
addition, the community develops many other libraries for Python. Ex: Pandas
is a widely used library for data analysis. Another reason why Python is popular
is because the syntax is concise and straightforward. The syntax of a language defines how code must be
structured. Syntax rules define the keywords, symbols, and formatting used in programs. Compared to other
programming languages.
History
Python was conceived in the late 1980s by Guido van Rossum at the Centrum Wiskunde & Informatica (CWI) in
the Netherlands.
The Inspiration: Van Rossum wanted to create a successor to the ABC language that could handle
exceptions and interface with the Amoeba operating system.
The Name: Contrary to popular belief, Python is not named after the snake. Van Rossum was a big fan
of the British comedy troupe Monty Python’s Flying Circus, and he wanted a name that was "short,
unique, and slightly mysterious."
2
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
The Launch: Python 0.9.0 was released in 1991.
Major Milestones:
o Python 2.0 (2000): Introduced list comprehensions and garbage collection.
o Python 3.0 (2008): A major revision designed to fix fundamental design flaws. It was not
"backward compatible," meaning old Python 2 code wouldn't run on it. This was a painful but
necessary transition for the language's future.
Python consistently ranks as the #1 or #2 most popular programming language in the world (according to the
TIOBE Index and Stack Overflow surveys). Here is why:
Low Entry Barrier: Its syntax is very close to English. If you can read English, you can almost
understand Python code.
The "Batteries Included" Philosophy: Python comes with a massive standard library. You don't have to
write code for complex tasks like file compression or web protocols from scratch; the tools are already
there.
Massive Community: Because millions use it, there is a library for almost everything. If you have a
problem, someone has likely already fixed it and shared the solution.
Corporate Backing: Major tech giants like Google, Facebook (Meta), and Netflix use Python
extensively and contribute to its development.
Python is the "Swiss Army Knife" of programming. It is used across nearly every industry:
Frameworks: Django (for large, secure sites like Instagram) and Flask
(for smaller, flexible apps).
Use Case: Automatically moving files, scraping data from websites, or sending out thousands of
personalized emails.
3
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
D. Scientific Computing
Use Case: NASA uses Python for analyzing data from the James Webb Space Telescope.
E. Cybersecurity
Hackers and security experts use Python for penetration testing, malware analysis, and network scanning
because it allows them to write tools very quickly.
Summary Table
Explanation
This program represents a basic point-of-sale system used in stores, helping compute the total cost of
items purchased by a customer.
Most modern terminals support ANSI escape codes. You can wrap your string in a specific "start" and
"end" code to change the formatting.
4
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
GETTING STARTED
In most programming languages, printing a simple message requires several lines of setup. In Python, it is just
one line:
print("Hello, World!")
What is happening?
Even though it is only one line, Python is doing several things behind the scenes:
1. The Function (print): print is a built-in function. You can think of a function as a "verb" or an action. Its
specific job is to send whatever is inside the parentheses to your screen (the standard output).
2. The Argument ("Hello, World!"): The text inside the parentheses is called an "argument." Because it is
surrounded by quotation marks, Python treats it as a String (a sequence of characters).
3. The Syntax: Notice there is no semicolon (;) at the end. Unlike C++ or Java, Python uses the end of the
line to signal the end of a command, keeping the code clean.
Explanation
name: This is a variable. You don't have to tell Python it's a "string" (text); it figures it out
automatically.
input(): This is a built-in function that talks to the user.
f"...": This is an "f-string," a modern way to format text by putting variables directly inside the quotes.
5
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example : Welcome Program Sample Output
print("===================================") ===================================
print(" PYTHON LEARNING SYSTEM ") PYTHON LEARNING SYSTEM
print("===================================") ===================================
What is your name? Ryan
name = input("What is your name? ") How old are you? 20
age = input("How old are you? ") What course are you taking? BSIT
course = input("What course are you taking? ")
Processing your information...
print("\nProcessing your information...\n")
------ USER PROFILE ------
print("------ USER PROFILE ------") Name : Ryan
print(f"Name : {name}") Age : 20
print(f"Age : {age}") Course : BSIT
print(f"Course : {course}")
Welcome to Python Programming!
print("\nWelcome to Python Programming!") Hi Ryan, we are glad to have you here.
print(f"Hi {name}, we are glad to have you here.") This program will help you begin your journey in coding.
print("This program will help you begin your journey in coding.")
Have a great learning experience!
print("\nHave a great learning experience!")
Explanation
This program collects basic personal information from the user, such as name, age, and course, then displays
the details in an organized format. The output shows a simple user profile and a personalized welcome message,
demonstrating how Python uses input, variables, and formatted printing to interact with users.
6
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
1.2 Input/Output
Learning objectives
BASIC OUTPUT
The print() function displays output to the user. Output is the information or result produced by a program.
The sep and end options can be used to customize the output. Table 1.1 shows examples of sep and end.
Multiple values, separated by commas, can be printed in the same statement. By default, each value is
separated by a space character in the output. The sep option can be used to change this behavior.
By default, the print() function adds a newline character at the end of the output. A newline character tells the
display to move to the next line. The end option can be used to continue printing on the same line.
In Python, sep and end are special "keyword arguments" used within the print() function to control how your
text is formatted on the screen.
By default, Python makes certain assumptions when you print things (like putting a space between items).
These two tools allow you to change those assumptions.
7
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
The sep Argument (Separator)
The sep parameter defines what character should be placed between multiple objects in a single print
statement.
Example:
# Default behavior (uses a space)
print("Apple", "Banana", "Cherry")
# Output: Apple Banana Cherry
Default: A newline character ("\n"), which move the cursor to the next line.
Purpose: To prevent Python from jumping to a new line, or to add a specific closing character.
Example:
# Default behavior (moves to a new line after printing)
print("Hello")
print("World")
# Output:
# Hello
# World
8
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Take Note: Spaces and newline characters are not inherently important. However, learning to be precise is an
essential skill for programming. Noticing little details, like how words are separated and how lines end, helps
new programmers become better.
Explanation
This example demonstrates how sep controls the separation between printed values, while end controls what
is printed at the end of each output line.
9
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Output Formatting Using sep and end
Objective: To demonstrate correct usage of the print() function’s sep and end parameters to
format output.
Sample Output
Instructions
End of Report
Code Section
10
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Basic Input
In Python, the input() statement is the primary bridge between the user and the computer. Without it,
programs would be "static," meaning they would do the same thing every time regardless of who is using
them.
By using variable = input("prompt"), you create a dynamic program that reacts to different data.
Computer programs often receive input from the user. Input is what a user enters into a program. An input
statement, variable = input("prompt"), has three parts:
A variable refers to a value stored in memory. In the statement above, variable can be replaced with any name
the programmer chooses. It is a reserved location in the computer's Random Access Memory (RAM). Think of it
as a labeled box.
Memory Allocation: When you write user_age = input(), Python sets aside a tiny piece of memory and
labels it user_age.
Naming Rules: While a programmer can choose almost any name, Python has rules:
o It must start with a letter or underscore (_).
o It cannot start with a number.
o It is case-sensitive (Name and name are two different boxes).
The Assignment Operator (=): In math, = means "equal to." In programming, it means "assign." It
takes the data from the right side and "moves" it into the variable on the left.
The input() function reads one line of input from the user. A function is a named, reusable block of code that
performs a task when called. The input is stored in the computer's memory and can be accessed later using the
variable.
A function is a pre-written tool. When you "call" input(), you are telling the Python interpreter to pause all
operations and wait.
The "Line" Rule: The input() function reads everything until the user presses the Enter key.
Data Type (The "Catch"): This is a critical technical detail—input() always returns a String (text).
o Even if the user types 25, Python stores it as "25" (text).
o If you want to do math with that input, you must "cast" or convert it using int() or float().
Reusability: Because the value is stored in a variable, you can use it 100 times throughout your
program without asking the user again.
A prompt is a short message that indicates the program is waiting for input. In the statement above,
"prompt" can be omitted or replaced with any message
The prompt is the user interface (UI) part of the code. It is a string literal placed inside the parentheses.
Communication: Without a prompt, the program will just show a blank screen with a blinking cursor.
The user won't know if the program is crashed or waiting for a name, a password, or a number.
Optionality: You can write name = input(). The program will still work, but it provides a poor "User
Experience" (UX).
11
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Clarity: Good prompts usually end with a space or a colon (e.g., "Enter your name: ") so the user's
typing doesn't run directly into the prompt text.
print("================================") ================================
print(" STUDENT INFORMATION FORM ") STUDENT INFORMATION FORM
print("================================") ================================
Enter your name: Ryan
name = input("Enter your name: ") Enter your course: BSIT
course = input("Enter your course: ") Enter your year level: 1st Year
year = input("Enter your year level: ")
Processing your information...
print("\nProcessing your information...\n")
------- STUDENT PROFILE -------
print("------- STUDENT PROFILE -------") Name : Ryan
print("Name :", name) Course : BSIT
print("Course :", course) Year : 1st Year
print("Year :", year)
Hello Ryan!
print("\nHello", name + "!") Welcome to the Python Programming course.
print("Welcome to the Python Programming course.") We hope this subject will help you develop
print("We hope this subject will help you develop your coding skills.") your coding skills.
Explanation
This program demonstrates how Python collects multiple pieces of information from the user and stores them
in variables. It then displays the data in a formatted profile and prints a personalized welcome message,
illustrating the basic concepts of input, output, and string formatting.
12
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Variables
Assignment statement
Variables allow programs to refer to values using names rather than memory locations. Ex: age refers to a
person's age, and birth refers to a person's date of birth. A statement can set a variable to a value using the
assignment operator (=). Note that this is different from the equal sign of mathematics. Ex: age = 6 or birth =
"May 15". The left side of the assignment statement is a variable, and the right side is the value the variable is
assigned.
A variable name can consist of letters, digits, and underscores and be of any length. The name cannot start with
a digit. Ex: 101class is invalid. Also, letter case matters. Ex: Total is different from total. Python's style guide
recommends writing variable names in snake case, which is all lowercase with underscores in between each
word, such as first_name or total_price.
A name should be short and descriptive, so words are preferred over single characters in programs for
readability. Ex: A variable named count indicates the variable's purpose better than a variable named c. Python
has reserved words, known as keywords, which have special functions and cannot be used as names for variables
(or other objects)
In mathematics, x = 5 means "x is the same as 5." In Python, x = 5 means "Take the value 5 and move it into
the memory location named x."
The "Overwrite" Rule: Unlike math, where x usually stays x, in programming, you can change a
variable's value at any time. If you say age = 20 and then age = 21, the "20" is thrown away and
replaced by "21."
13
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
2. Variables vs. Memory Locations
Computers don't actually know what "age" or "birth" means. They store data in complex hardware addresses
like 0x7ffee440a7bc.
Abstraction: It is much easier for a programmer to write total = price + tax than to try and remember
which physical hardware slot holds the price.
Technical
Part Rule
Name
Must be a variable name. You cannot put a number here (e.g., 10 = x will cause
Left Side L-value
an error).
Right Can be a raw value (6), a string ("May 15"), another variable, or a math expression
R-value
Side (6 + 4).
To truly master Python, you must understand where math logic and programming logic diverge:
x=x+1
score = 10
score = score + 1
Discussion: Python looks at the Right Side first. It sees 10 + 1, calculates 11, and then assigns that new value
back into the score box. The variable score is now 11.
14
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Summary Table: Assignment Examples
new_age = age Looks up age (25) and copies it to new_age. Both are 25
If you break these rules, Python will show a SyntaxError and your program will not run.
Must start with a letter or underscore: A variable name must begin with a letter ($a-z, A-Z$) or an
underscore (_). It cannot start with a number.
o ✅ name = "Alex"
o ✅ _id = 101
Only Alphanumeric characters and underscores: Aside from the first character, the rest of the name
can contain letters, numbers, and underscores. No special symbols like @, $, #, or % are allowed.
o ✅ user_score_2 = 100
o ✅ my_variable = 10
o ❌ my variable = 10 (Invalid)
Case Sensitivity: Python is case-sensitive. age, Age, and AGE are three completely different variables.
Reserved Keywords: You cannot use words that are already "taken" by Python (keywords that have
special meanings).
15
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
2. Naming Conventions (PEP 8)
These are the "social rules" followed by professional Python developers to keep code readable. The official
style guide is called PEP 8.
In Python, the most common way to write multi-word variables is snake_case (all lowercase with
underscores).
user_home_address
total_invoice_amount
Descriptive Names
Constants
If you have a variable that never changes (like the speed of light), programmers usually write it in ALL CAPS.
GRAVITY = 9.8
MAX_LOGIN_ATTEMPTS = 5
_temp ✅ Valid Starts with underscore (often used for internal data).
userName ⚠️ Valid but... This is "CamelCase." Common in Java, but not standard in Python.
16
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output
Explanation
In this program, RATE_PER_KWH is treated as a constant because its value does not change throughout the
program, while customer_name, units_used, and total_bill are variables that store data which may
change. This demonstrates how Python uses constants for fixed values and variables for storing and
manipulating information in real-world applications.
17
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Student Information Using Input and Variables
18
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
String Basics
Learning objectives
Quote marks
A string is a sequence of characters enclosed by matching single (') or double (") quotes. Ex: "Happy
To include a single quote (') in a string, enclose the string with matching double quotes ("). Ex: "Won't this
work?" To include a double quote ("), enclose the string with matching single quotes ('). Ex: 'They said "
In programming, text is referred to as a String, because it is a "string" or sequence of individual characters tied
together.
Python allows you to use either single quotes (') or double quotes ("). The key rule is that they must match at
the beginning and end.
Flexibility with Quotes: The reason Python provides both is to make it easy to include actual quote
marks inside your text without "breaking" the string.
19
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Goal Method Example
Include a single quote Use double quotes on the outside. "It's a beautiful day"
Include double quotes Use single quotes on the outside. 'He said, "Hello!"'
The len() function is a built-in tool that counts the number of characters in a string.
Crucial Note: Python counts everything—letters, numbers, punctuation, and even spaces.
Example:
print(len(phrase))
In math, + adds numbers. In Python strings, + performs concatenation, which means "gluing" strings together
end-to-end.
Rule: You can only concatenate a string to another string. You cannot "add" a string to a number
without converting the number first.
Example:
first_name = "Alan"
last_name = "Turing"
full_name = first_name + " " + last_name
print(full_name)
# Output: Alan Turing
'21' is a string. Python sees it as the character '2' followed by '1'. You cannot do math with it.
20
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
HANDLING ERRORS
If you try to mix quotes incorrectly, Python gets confused about where the string ends:
❌ print('It's working') — Error! Python thinks the string is 'It' and doesn't know what to do with the
leftover s working').
Remember!
first_name = "Ryan"
last_name = "Agsaluna"
First Name: Ryan
full_name = first_name + " " + last_name Last Name: Agsaluna
length = len(full_name) Full Name: Ryan Agsaluna
Number of characters in full name: 13
print("First Name:", first_name)
print("Last Name:", last_name)
print("Full Name:", full_name)
print("Number of characters in full name:", length)
Explanation
This program combines two strings using the + operator to create a full name and then uses the len() function
to count the total number of characters in the combined string. It demonstrates how Python manipulates text
data and measures string length for practical applications such as generating usernames or validating input.
21
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example User Profile Generator (Using + for Output) Sample Output
first_name = "Ryan"
last_name = "Agsaluna" Full Name: Ryan Agsaluna
age = 20 Age: 20
Number of characters in name: 13
full_name = first_name + " " + last_name
name_length = len(full_name)
Explanation
This program combines string and integer data by converting numerical values into strings so they can be
concatenated using the + operator. It reinforces the concept of variables, string manipulation, and basic type
conversion in Python.
first_name = input("Enter your first name: ") Enter your first name: Ryan
last_name = input("Enter your last name: ") Enter your last name: Agsaluna
age = int(input("Enter your age: ")) Enter your age: 20
Explanation
This version reinforces input, string concatenation, type conversion, and string length calculation, which are
essential beginner concepts in Python.
22
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Output Formatting Using sep and end
Objective: To demonstrate mastery of string variables, user input, string concatenation, and
structured output formatting.
Sample Output
Instructions
1. Ask the user to enter the following Enter first name: Ryan
information and store each one in a Enter last name: Agsaluna
separate variable: Enter position: System Developer
first_name, last_name, position, Enter company: TechNova Solutions
company, address, and year. Enter address: Iloilo City
2. Construct complete sentences using Enter year established: 2026
only string concatenation (+).
3. Do not use format() or f-strings. EMPLOYEE PROFILE
4. The program must display the output in ------------------------------------------
the format shown in the Desired Ryan Agsaluna works as a System Developer at TechNova
Output. Solutions.
He/She is currently based in Iloilo City.
TechNova Solutions was established in 2026.
Code Section
23
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Number Basics
Learning objectives
Python supports two basic number formats, integer and floating-point. An integer represents a whole number,
and a floating-point format represents a decimal number. The format a language uses to represent data is called
a data type. In addition to integer and floating-point types, programming languages typically have a string type
for representing text
An integer is a whole number. It can be positive, negative, or zero, but it can never have a decimal point.
You can always check what type of data is stored in a variable by using the built-in type() function. This is very
useful for debugging.
x = 10
y = 10.5
z = "10"
print(type(x)) # Output: <class 'int'>
print(type(y)) # Output: <class 'float'>
print(type(z)) # Output: <class 'str'>
24
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
4. Mixing Types (Implicit Conversion)
Python is smart when it comes to math. If you perform an operation between an int and a float, Python
automatically converts the result to a float to avoid losing the decimal precision.
Example:
a = 5 # int
b = 2.0 # float
result = a + b
print(result) # Output: 7.0 (a float)
Data Type Python Name Description Example Remember: Why does "Data Type" matter?
As we discussed, if you put quotes around a number, it is no longer numeric data; it becomes a string.
10 + 10 = 20 (Math)
"10" + "10" = "1010" (Text joining/Concatenation)
quiz = 85
exam = 90.5 Quiz Score: 85
project = 80 Exam Score: 90.5
Project Score: 80
total = quiz + exam + project Total Score: 255.5
average = total / 3 Average Score: 85.17
This program mixes whole numbers and decimal numbers in mathematical operations and
Explanation formats the computed average to two decimal places for proper presentation. It
demonstrates both numerical processing and basic output formatting in Python.
25
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Basic Arithmetic
Arithmetic operators are used to perform mathematical operations like addition, subtraction, multiplication,
and division.
Python uses standard symbols for basic math, but remember that the result's data type can change depending
on the operator.
# 2. Subtraction
subtraction = a - b
print("Subtraction (15 - 4):", subtraction)
Explanation
# 3. Multiplication
multiplication = a * b
print("Multiplication (15 * 4):", multiplication) The Float Result: Notice that in the Division example, the
output is 3.75. Even if we had divided 16 / 4, Python would have
# 4. Division given us 4.0. As discussed, the / operator always outputs a float
division = a / b to maintain decimal precision.
print("Division (15 / 4):", division)
The Power of Parentheses: Look at the last two lines. By simply
# 5. Demonstrating Precedence adding () around the addition, we changed the outcome from 7
precedence_1 = 1 + 2 * 3 to 9. This is because parentheses tell Python: "Stop everything
precedence_2 = (1 + 2) * 3 else and do this first."
print("Precedence (1 + 2 * 3):", precedence_1)
print("Precedence ((1 + 2) * 3):", precedence_2)
26
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Assignment with Operators
Python also allows a "shortcut" called Augmented Assignment. If you want to add 5 to an existing variable,
you don't have to write x = x + 5. You can write:
score = 10
score += 5 # This is the same as score = score + 5
print(score) # Output: 15
This works for all basic operators: +=, -=, *=, and /=.
Operator precedence
When a calculation has multiple operators, each operator is evaluated in order of precedence. Ex: 1 + 2 * 3 is 7
because multiplication takes precedence over addition. However, (1 + 2) * 3 is 9 because parentheses take
precedence over multiplication.
1. Parentheses ()
Expression: 1 + 2 * 3
Final Result: 7
Expression: (1 + 2) * 3
2. 3 * 3 = 9.
Final Result: 9
27
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
3. The Division Rule
In Python, the division operator (/) is special. Even if you divide two whole numbers that result in a whole
number, Python will convert it to a float.
This ensures that if there is a remainder (like 5 / 2 = 2.5), the data is not lost.
As a programmer, it is considered "Best Practice" to use parentheses even when they aren't strictly necessary.
It makes the code easier for humans to read.
Both give the same answer, but the second version tells other programmers exactly what your intention was.
# Example 2: Forcing Addition first with Parentheses 1. Why is Example 1 equal to 20?
Many beginners expect the answer to be 30 because they read left-to-
# Calculation: (10 + 5) * 2
right (10 + 5 = 15, then 15 x 2 = 30). However, Python follows the
result_parentheses = (x + y) * z Multiplication First rule. It calculates 5 x 2 first to get 10, then adds the
10 from the variable x.
# Example 3: Complex combination
2. Why is Example 3 a Float (25.0)?
# Calculation: 100 / 10 + 5 * (2 + 1)
Notice the .0 at the end of the final result. Even though every number we
# 1. (2 + 1) = 3 used was a whole number, the presence of the Division operator (/)
# 2. 100 / 10 = 10.0 automatically turns that part of the equation into a float. Once one part
# 3. 5 * 3 = 15 of an addition becomes a float, the whole answer becomes a float to
ensure accuracy.
# 4. 10.0 + 15 = 25.0
complex_math = 100 / x + y * (z + 1) 3. The "Left-to-Right" Tie-Breaker
What happens if we have 10 / 2 * 5? Both Division and Multiplication
print("Standard Precedence (10 + 5 * 2):", result_standard) have the same level of precedence. In this case, Python uses the Left-to-
Right rule:
print("Using Parentheses ((10 + 5) * 2):", result_parentheses)
1. It does 10 / 2 = 5.0
print("Complex Equation (100 / 10 + 5 * (2 + 1)):", complex_math) 2. It does 5.0 x 5 = 25.0
28
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Summary of Precedence Levels
Explanation
This program simulates a grocery store purchase where Python applies operator precedence by calculating
multiplication and division before addition and subtraction. By using parentheses, the order of com putation
changes, producing a different total and clearly demonstrating how precedence affects real-world calculations.
29
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Grocery Store Bill Calculation Sample Output
Explanation
This version reinforces input handling, type conversion, and operator precedence within a practical real-world
context.
30
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Common Types of Errors
Different types of errors may occur when running Python programs. When an error occurs, knowing the type
of error gives insight about how to correct the error. The following table shows examples of mistakes that
anyone could make when programming.
Comments
A comment is a note written within the source code that is entirely ignored by the Python interpreter. When
Python sees the hash character (#), it stops reading that line and moves immediately to the next one.
As your text mentions, context matters. The # only creates a comment if it is "loose" in the code.
There are three main reasons why professional programmers use comments:
1. Explanation (The "Why"): Code tells the computer how to do something. Comments tell humans why
you chose to do it that way.
2. Organization: They act like "headings" in a book, marking where different sections of a program start
(e.g., # --- Database Configuration ---).
3. Testing (Commenting Out): You can "turn off" a line of code temporarily by putting a # in front of it.
This is great for debugging without deleting your work.
31
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
3. Best Practices for Writing Comments
Your notes highlight two very important "Pro-Tips" for clean code:
Don't use comments to restate what the code clearly says. Instead, describe the intent.
Docstrings
While the hash character (#) is used for short, internal notes, Docstrings (short for Documentation Strings) are
used for larger, more formal explanations.
32
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
In Python, a docstring is created by enclosing text in triple quotes (""" or '''). Unlike regular comments,
docstrings are actually stored as part of the code, allowing Python to use them to generate automatic help
menus.
1. Defining a Docstring
A docstring can span multiple lines without needing a # on every line.
"""
This is a multi-line docstring.
It is used to explain how a program, function, or class works
in great detail.
"""
print("The program is running!")
Code Section
34
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
CHAPTER II: Understanding Python Expressions
This chapter explores essential Python concepts that build a strong foundation for programming proficiency. It
introduces the Python shell as the primary environment for writing and testing code, then explains type
conversion, mixed data types, and common issues such as floating-point errors and dividing integers. The
discussion also covers the use of the math module for advanced mathematical operations and proper formatting
of code to improve readability and maintainability. Finally, the chapter presents the basics of lists and tuples,
enabling learners to store, organize, and manage collections of data effectively.A computer program is
essentially a sequence of instructions, called statements that execute in order. In Python, many of these
statements contain one or more expressions.
What is an Expression?
An expression is a snippet of code that represents a single value to be computed. Even a single value on its
own can be an expression.
Expressions are highly flexible; they can be as short as a single number or arbitrarily long, spanning multiple
complex calculations.
While you may already be familiar with basic expressions like 1 + 2 or "Hi " + "there", this chapter dives deeper
into advanced numeric and string operations. You will learn how to:
Mastering expressions is the key to unlocking more complex and interesting programming calculations.
The Python Shell is a command-line interface that allows you to interact with the Python interpreter in real-
time. It follows the REPL pattern:
35
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
2. Eval: It evaluates (executes) the code.
3. Print: It prints the result to the screen.
4. Loop: It starts over and waits for your next command.
When to use it: It is perfect for testing a single line of code, checking the value of a variable, or doing quick
math.
print("Welcome,", customer)
print("Membership Duration:", membership_years, "years")
Explanation
This program simulates a store membership system where the user enters customer data through the Python
shell. It demonstrates how Python receives input, converts data types, performs computation, and displays
output.
36
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Daily Allowance Tracker
Objective: To compute total monthly expenses and determine the remaining budget using basic
input and arithmetic operations.
Sample Output
Instructions
1. Input the monthly income and four categories of Monthly income: 25000
expenses. Rent: 8000
2. Compute the total expenses. Food: 6000
3. Compute the remaining balance. Transportation: 3000
4. Display a clear summary report Utilities: 2000
37
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Type Conversion
In Python, Type Conversion is the process of changing a value from one data type to another. This is crucial
because Python must know exactly what "kind" of data it is dealing with to perform operations like math or
text joining.
There are two ways this happens: Implicitly (by the computer) and Explicitly (by the programmer).
Implicit conversion happens automatically when Python realizes an operation requires a change in data type to
maintain accuracy or accommodate new data.
How it works: Python "promotes" the variable to a more complex type (like an int to a float) without the
programmer writing any extra code.
Explicit conversion (also known as Type Casting) is when the programmer uses built-in functions to force a
data type change. This is most commonly used when dealing with user input.
38
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Code:
print(f"Sum: {sum_result}")
print(f"int(5.9) becomes: {converted_int}")
print(message)
Comparison Summary
39
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Type Conversion (Casting)
Python is strongly typed, meaning it won't let you perform operations on incompatible types (like adding "5"
to 5). You must manually convert them using constructor functions.
int(value): Converts data to an integer. It truncates (cuts off) decimals; it does not round them. int(3.9)
becomes 3.
float(value): Converts data to a decimal. float(5) becomes 5.0.
str(value): Converts data to a string. Essential for concatenating numbers with text.
employee = input("Enter employee name: ") Enter employee name: Alex Rivera
hours = int(input("Enter hours worked: "))
rate = float(input("Enter rate per hour: ")) Enter hours worked: 40
Explanation
The program converts user input into appropriate data types (integer and float) before performing arithmetic
operations. This demonstrates the importance of type conversion in real-world financial calculations.
40
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Online Shopping Checkout
Objective: To apply type conversion and arithmetic operations to compute an online shopping bill.
Customer: Ryan
Subtotal: 3601.5
Tax: 432.18
Shipping: 150.0
Code Section Total Due: 4183.68
41
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
3. Mixed Data Types (Coercion)
When an expression contains both integers and floating-point numbers, Python automatically converts the
integer to a float. This is called Implicit Type Conversion.
Why Python does this: To preserve precision. If Python converted 5 + 2.5 to an integer, it would have to throw
away the .5, leading to incorrect data.
Whenever an operation involves both an int and a float, Python automatically "promotes" the result to a float.
Why? Because a float is more "precise" than an integer. If Python forced the result to be an integer, it would
have to throw away decimal data, leading to mathematical errors.
print(f"Result: {total}")
print(f"Data Type of total: {type(total)}")
Explanation: Even though 3 x 5 is exactly 15 Python prints 15.0. The presence of the decimal point tells you
that the variable total is stored as a float.
It is a common mistake to think that dividing two whole numbers results in an integer. In Python 3, the
standard division operator (/) always produces a float, even if there is no remainder.
Example Code:
result = 10 / 2
Output:
print(result) 5.0
print(type(result)) <class 'float'>
42
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
3. Combining Numbers and Strings
While Python handles int and float mixtures automatically, it cannot automatically mix numbers and strings.
You must use explicit type conversion (Casting) to make them compatible.
age = 25 # int
# This will cause a TypeError:
# print("You are " + age + " years old.")
A common trap for new programmers: Type Incompatibility. While Python is smart enough to mix integers
and floats, it draws a hard line between text (strings) and numbers.
In Python, you cannot perform mathematical operations between a string and a number. This often causes the
"Noor's Program" error, where a user inputs a number, but Python treats it like text.
43
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Code: The "Noor" Scenario
While you cannot add a string and an integer, you can use the multiplication operator. When used with a
string and an integer, * becomes the Repetition Operator.
Example Code:
44
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
The f-string Solution
Instead of constantly using str() to convert numbers for printing, Python programmers use f-strings. They
handle the conversion for you automatically inside the curly braces.
points = 50
# No manual str() needed!
print(f"You have {points} points.")
student = input("Enter student name: ") Enter student name: Jordan Smith
age = int(input("Enter age: ")) Enter age: 20
gpa = float(input("Enter GPA: ")) Enter GPA: 3.85
Student: Jordan Smith
print("Student:", student) Age: 20
print("Age:", age) GPA: 3.85
print("GPA:", gpa)
Explanation
This program uses mixed data types—string, integer, and float—within the same application. It reflects how
real systems store and process different types of information simultaneously.
45
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Academic Performance Report
Objective: To compute a student's weighted final grade using mixed numeric data types
1. Input the student's name, quiz average, project score, Student name: Anna
and exam score. Quiz average: 88
2. Compute the weighted final grade. Project score: 92
3. Display the student's academic report. Final exam score: 85
Student: Anna
Final Grade: 88.1
Code Section
46
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
2.4 Floating-Point Errors (Precision Issues)
Computers store numbers in binary (base-2). Many decimal fractions (base-10), such as $0.1$ or $0.3$, cannot
be represented perfectly in binary. They become repeating decimals, much like how $1/3$ is $0.3333...$ in our
base-10 system.
The Danger:
Solution: When comparing floats, use round() or check if the difference is smaller than a tiny threshold (e.g.,
abs(a - b) < 0.00001).
one of the most surprising facts about computer science: computers cannot represent most decimal
numbers perfectly. This leads to tiny inaccuracies that can accumulate and cause bugs if not handled
properly.
Computers use the Binary System (0s and 1s) to store data. While whole numbers like $5$ (binary 101) are
easy to represent, fractions are much harder.
In our standard decimal system (Base-10), we cannot represent 1/3 perfectly ($0.3333... repeating). Similarly,
in the computer's binary system (Base-2), it is impossible to represent simple decimals like 0.1 or 0.2 perfectly.
When you type 0.1, Python stores the closest possible binary approximation. When that approximation is
converted back to decimal, it looks like:
0.1000000000000000055511...
A round-off error is the mathematical difference between the true value (e.g., $0.1$) and the approximation
stored in memory. While this difference is tiny, it becomes visible when you perform math.
You can see these errors yourself by adding $0.1$ and $0.2$. Mathematically, the answer is $0.3$, but Python
will show something slightly different.
47
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output
To mitigate (lessen) these errors, Python provides the round() function. It forces a number to a specific number
of decimal places, "cleaning up" the tiny binary inaccuracies for the user.
Syntax:
round(number, ndigits)
number: The float you want to round.
ndigits: (Optional) The number of decimal places.
pi_approx = 3.14159265
# Round to 2 decimal places
print("Two decimals:", round(pi_approx, 2))
Two decimals: 3.14
Nearest integer: 3
# Round to nearest integer (no second argument)
print("Nearest integer:", round(pi_approx))
Explanation
This activity illustrates floating-point precision errors that occur when computers store decimal values. It helps
students understand why some results appear slightly inaccurate.
48
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Investment Simulator
Objective: To observe the effect of floating-point arithmetic when summing small decimal
values.
Sample Output
Instructions
Total Investment:
1.0000000000000002
Code Section
49
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
2.5 Dividing Integers: / vs //
In Python, integer division is more than just getting a decimal answer. It provides two specialized tools—Floor
Division and Modulo—that allow you to break numbers apart into "whole parts" and "leftovers." This is
essential for real-world tasks like timekeeping, currency, and unit conversions.
1. True Division (/): Always results in a float, even if the numbers divide perfectly. 4 / 2 is 2.0.
2. Floor Division (//): Divides and rounds down to the nearest whole number. This is useful for things like
calculating "how many full weeks are in 20 days."
Example:
print(20 / 7) # 2.857...
print(20 // 7) # 2 (The remainder is discarded)
When you divide two numbers in Python, you have three different operators to choose from depending on
what information you need.
A very common pattern in programming is using // and % with the same number (the modulus) to split a large
value into smaller units.
To find the larger unit (meters), you use floor division by 100.
To find the smaller unit (centimeters), you use modulo by 100.
Example Code:
print(f"Total: {total_cm}cm")
print(f"Conversion: {meters}m and {remaining_cm}cm")
50
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
3. Real-World Application: Time Conversion
Floor division and modulo are most famously used for time. If a video is 135 seconds long, how many minutes
and seconds is that?
Example Code:
Quotient: The result of //. It tells you "How many full groups?"
Remainder: The result of %. It tells you "What didn't fit into a full group?"
Modulus: The number you are dividing by (e.g., in x % 12, the modulus is 12).
Pronunciation: Programmers read 7 % 4 as "Seven mod four."
Summary Checklist
Explanation
The program demonstrates both normal division and integer division. This is important in logistics where both
exact values and whole units matter.
51
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Manufacturing Distribution
Objective: To observe the effect of floating-point arithmetic when summing small decimal
values.
Sample Output
Instructions
1. Input the total number of products, crates, and pallets. Total products: 245
2. Compute the distribution results.
Number of crates: 12
3. Display all computed values.
Number of pallets: 7
Per Crate: 20
Remaining after crates: 5
Per Pallet: 35
Remaining after pallets: 0
Code Section
52
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
2.6 The Math Module
Python can do basic math (addition, subtraction, etc.) automatically, scientists and engineers often need more
advanced tools. These tools are stored in the Math Module.
For functions beyond + and -, Python provides the math module. This is a library of pre-written mathematical
tools.
Example Code:
import math
radius = 5
# Area = pi * r^2
area = [Link] * [Link](radius, 2)
print(f"Area is: {area:.2f}")
1. What is a Module?
A module is a file containing pre-written code that you can "borrow" for your own program. Think of it like a
specialized toolbox that you only bring out when you need it.
Built-in Functions: These are "always on" (like print(), input(), and type()). You don't need to do
anything special to use them.
Module Functions: These are stored in the Standard Library. You must use the import statement to
access them.
To use the math module, you place import math at the very top of your code. To call a specific function from
that module, you use dot notation: module_name.function_name().
53
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
3. Common Math Functions and Constants
The math module is packed with tools. Here are the most frequently used ones:
Let's combine the math module with user input to calculate the area of a circle (Area = pi r^2).
import math
# 3. Output result
print(f"A circle with radius {radius} has an area of {area:.2f}")
Summary
54
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output
Explanation
This program introduces Python’s math module for performing accurate mathematical operations. It reflects
real-world usage in engineering and construction calculations.
Objective: To apply the math module in computing land and pond areas.
55
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
2.7 Formatting Code (The Human Element)
Proper formatting is essential for creating code that is easy to read and maintain. While extra or missing spaces
often do not change how a program runs, they can make code difficult for humans to understand. Code isn't
just for computers; it's for people. Python emphasizes "clean" code through formatting.
1. Whitespace: Use one space around operators (x = 5 + 2) to let the code "breathe."
2. f-strings: Introduced in Python 3.6, these are the most efficient way to format text.
o print(f"Value: {val:.2f}") — The .2f tells Python to show exactly 2 decimal places.
3. Indentation: Python uses 4 spaces per indentation level. This isn't just for looks; it's how Python
defines blocks of code (like in if statements).
To ensure consistency and readability, the Python community follows specific spacing guidelines.
Assignment: One space before and name = input("Your name? name=input("Your name?") or name
after the = sign. ") =input("Your name? ")
Example: In the expression x**2 + 5*x - 8, notice there are no spaces around the exponent (**) or
multiplication (*) operators.
56
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
This visually communicates that those operations happen first before the addition and subtraction,
which are separated by spaces.
Example Comparison
When writing code, readability is just as important as functionality. One major challenge is handling very long
strings or statements that exceed the width of your screen. To keep code clean and manageable, Python
developers follow specific standards for line length and use various techniques to break code across multiple
lines.
PEP 8, the official style guide for Python, recommends that each line of code be limited to fewer than 80
characters.
This prevents programmers from having to scroll horizontally to read a full line of code.
It allows multiple code files to be open side-by-side on a single monitor effectively.
PEP 8 is the official style guide for Python code. It stands for Python Enhancement Proposal #8.
57
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
In programming, "style" refers to how the code looks—where you put spaces, how you name variables, and
how you organize lines—rather than what the code actually does. Because Python was designed to be highly
readable, PEP 8 was created to ensure that all Python developers write code in a consistent way.
The main goal of PEP 8 is summed up by one of Python's creators: "Code is read much more often than it is
written."
1. Indentation
2. Naming Conventions
4. Whitespace
5. Imports
Rule: Imports should be on separate lines at the very top of the file.
Correct:
import os
import sys
58
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
2. Automatic Concatenation
When you place two or more string literals (text in quotes) next to each other, Python automatically joins them
into a single string. This is incredibly useful for breaking a long sentence into shorter, readable chunks within a
print() function without using the + operator.
# Breaking a long sentence into readable lines This is a very long sentence that we are breaking
print("This is a very long sentence that we are breaking up " up into multiple lines so that it is easier to read in
"into multiple lines so that it is easier to read " our code editor without scrolling.
"in our code editor without scrolling.")
3. Multi-line Statements
Sometimes a single command or variable assignment is too long for one line. Python offers two ways to handle
this: Explicit and Implicit line joining.
You can use a backslash (\) at the end of a line to tell Python that the statement continues on the next line.
This is the preferred method according to PEP 8. If a statement is wrapped in parentheses (), brackets [], or
braces {}, Python automatically knows it continues until it finds the closing character.
# Explicit Line Joining (Less common/Not recommended) This uses a backslash to join lines.
line_1 = "This uses a backslash " \ This uses parentheses to join lines naturally.
"to join lines."
print(line_1)
print(line_2)
59
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output
Explanation
The program demonstrates formatted output to display monetary values correctly. Proper formatting is
essential in business and financial applications.
Guest: Mark
Code Section Room Cost: ₱7352.25
Service Charge: ₱735.23
Total Bill: ₱8087.48
60
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Additional Formatting
Unicode
Python uses Unicode, the international standard for representing text on computers. Unicode defines a
unique number, called a code point, for each possible character. Ex: "P" has the code point 80, and "!" has the
code point 33.
The built-in ord() function converts a character to a code point. Ex: ord("P") returns the integer 80.
Similarly, the built-in chr() function converts a code point to a character. Ex: chr(33) returns the string "!".
Unicode is an extension of ASCII, the American Standard Code for Information Interchange. Originally, ASCII
defined only 128 code points, enough to support the English language. Unicode defines over one million code
points and supports most of the world's written languages.
61
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Special characters
An escape sequence uses a backslash (\) to represent a special character within a string.
F-strings
A formatted string literal (or f-string) is a string literal that is prefixed with "f" or "F". A replacement field
is an expression in curly braces ({}) inside an f-string. Ex: The string f"Good morning, {first} {last}!" has two
replacement fields: one for a first name, and one for a last name. F-strings provide a convenient way to
combine multiple values into one string.
62
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output
# Defining variables
first = "Noor"
last = "Ahmed" Good morning, Noor Ahmed! Your score is 95.5.
score = 95.5 Next year, your score could be 97.5!
print(message)
# You can also perform math directly inside the curly braces
print(f"Next year, your score could be {score + 2}!")
Sample Output
Example
# Using f-strings with format specifiers and correct comma spacing Growth Rate: 5 Next Year: 12,962,961
print(f"Current Population: {population:,d}")
63
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Tuple and List Basics
A list in Python is a versatile object used to bundle multiple elements together into a single variable. They are
one of the most fundamental data structures in the language.
1. Defining Lists
Lists are defined by placing comma-separated values inside square brackets [].
Standard List: list_1 = [1, 2, 4]
Mixed Data Types: Lists are not restricted to one type; they can contain integers, strings, floats, or
even other lists simultaneously.
Empty Lists: You can create a list with no items if you plan to add data to it later.
4. Explanation
Bundling: In the my_data example, notice how Python stores 2 (int), "Hello" (str), and 2.5 (float)
together without error. This flexibility makes lists the "Swiss Army Knife" for storing collections of data.
Square Brackets vs. Parentheses: It is important to remember that lists must use square brackets [].
Using parentheses () would create a different object called a tuple.
The list() Function: While [] is more common for creating empty lists, list() is a built-in function often
used when you want to convert other types of data (like a string) into a list format.
Tuple
In Python, a tuple is a data structure used to store a sequence of items. While they look similar to lists, they
have distinct characteristics that make them useful for specific programming tasks.
1. Defining and Creating Tuples
64
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
A tuple is defined by a sequence of comma-separated values. While the commas are what technically define
the tuple, it is standard practice to surround the sequence with parentheses ().
Mixed Types: Like lists, a tuple can contain elements of different types, such as integers, strings, and
floats.
Convention: Always use parentheses for better readability.
65
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Summary
At this point, you should be able to write programs that ask for input of mixed types, perform mathematical
calculations, and output results with better formatting. The programming practice below ties together most
topics presented in the chapter.
66
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output
print("Inventory:", inventory)
print("Departments:", departments)
Explanation
This activity demonstrates how lists store changing data while tuples store fixed categories. It models how
businesses organize inventory information.
67
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
CHAPTER III – Control Structures
Chapter III introduces control structures, beginning with the concept of Boolean values, which represent
either True or False, and the use of comparison and logical operators to evaluate expressions and produce
Boolean results. It also explains how operators are evaluated according to precedence and associativity, and
how conditions are formed from expressions that result in True or False. The chapter then focuses on decision
statements, which allow programs to follow different paths of execution based on given conditions, including
the ability to nest decision statements within one another for more complex logic. Finally, it presents
conditional expressions as a concise, single-line alternative to traditional if–else statements, enhancing both
readability and efficiency of code.
A Boolean value represents one of two possible states: True or False. These are the foundation of all computer
decision-making. In Python, True and False must always be capitalized. The bool data type (short for
Boolean) is the simplest data type in Python, These values are essential for controlling the flow of a
program through decisions.
Binary Nature: A Boolean value can only ever be one of two things: True or False.
Keywords: In Python, True and False are reserved keywords.
Strict Capitalization: Python is case-sensitive; you must capitalize the first letter for the interpreter to
recognize them as Boolean values.
o True is a valid Boolean.
o true (lowercase) will result in a NameError because Python thinks it is a variable name.
Booleans are often the result of comparisons (like "Is 10 greater than 5?") or are used as "flags" to track the
state of a program.
Binary Questions: Just as people answer "yes/no" to a question like "Do you like pineapple on pizza?",
Python uses bool to store that answer internally.
Memory: Because Booleans only have two states, they are very efficient for a computer to store and
process.
The "bool" label: When you check the type of these values using type(), Python labels them as <class
'bool'>.
# Checking types
print(f"The data type of 'True' is: {type(is_python_fun)}")
69
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Explanation
Binary Nature: Booleans function like a light switch. They can only exist in one of two states: True
(on/1) or False (off/0). This is the foundation of all computer logic.
Reserved Keywords: In Python, True and False are special keywords used to represent these states.
Because they are "reserved," you cannot use these names for your own variables or functions.
Strict Capitalization: Python is extremely specific about case sensitivity.
o Valid: True and False (Upper-case 'T' and 'F').
o Invalid: true or false (Lower-case). If you type them in lower-case, Python will search for a
variable with that name and, finding none, will throw a NameError.
# Equality check
is_perfect_score = (my_score == 100)
# Not equal to
is_not_zero = (my_score != 0)
print(f"Score: {my_score}")
print(f"Is the score passing? {is_passing}")
print(f"Is it a perfect score? {is_perfect_score}")
print(f"Is the score non-zero? {is_not_zero}")
Explanation
1. Comparison Operators: These are symbols used to compare two values. Common ones include >
(greater than), < (less than), == (equal to), and != (not equal to).
2. Resulting in Booleans: Every time you use a comparison operator, Python evaluates the expression
and returns exactly one thing: a Boolean (True or False).
3. The Equality Sign (==): A common mistake is using a single = for comparison. In Python, a single =
assigns a value to a variable, while a double == compares two values to see if they are the same.
4. Expressions: The statement my_score > passing_score is called a Boolean expression. It is a piece of
code that Python "boils down" to a single Boolean result.
70
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
3.2 if and If-else Statements
An if statement checks a condition. If the condition is True, the indented block of code runs. If it is False, the
else block (if provided) runs instead. An if statement is a decision-making structure that allows a program to
execute a specific block of code only when a certain condition is met. Just as you might decide to grab an
umbrella only if the weather is rainy, a program uses these statements to decide which operations to perform
based on a variable's value.
1. Components of an if Statement
Basic Format
if condition:
statement(s)
is_rainy = True
Explanation
The Condition: The variable is_rainy is True and Execution: Because the condition evaluates to true,
the program enters the indented body and prints "Grab an umbrella!".
Continuation: Regardless of the if statement, the program always continues to the last line because it
is not indented.
71
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
2. If with Numeric Comparison
Programs often perform operations based on a variable's value, such as checking for errors.
Sample Output
Example
# A program adds two numbers. If the result is negative, the program prints an
error.
num1 = 10 Error: The total is a negative
num2 = -50 number.
total = num1 + num2
Explanation
password_attempt = "12345"
Explanation
Multiple Statements: The body can contain multiple lines of code, as long as they all have the same
level of indentation
Skipping: If password_attempt had been "qwerty", the condition would be False, and both print
statements would have been skipped.
72
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
2. The if-else Structure
While a simple if statement performs an action when a condition is true, an if-else statement provides an
alternative path. It performs one operation when the condition is True and a completely different operation
otherwise (when the condition is False).
Basic Format
if condition:
# This block runs if the condition is True
print("The condition was met!")
else:
# This block runs if the condition is False
print("The condition was not met!")
Formatting Requirements
Indentation: Both the if and else bodies must be indented by one level (conventionally four spaces).
Colons: Both the if condition and the else keyword must end with a colon (:).
Grouping: All statements within a specific body must share the same indentation level to be grouped
together.
In this scenario, a program checks if a student passed a test based on a minimum score.
score = 65
passing_grade = 70
Result: Fail.
# The condition checks if the score is 70 or higher Please schedule a retake.
if score >= passing_grade:
print("Congratulations!")
print("You passed the exam.")
else:
# This block runs because 65 is less than 70
print("Result: Fail.")
print("Please schedule a retake.")
73
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Explanation
This example uses the modulo operator (%) to decide if a number is even or odd.
number = 14
14 is an Even number.
if number % 2 == 0:
print(f"{number} is an Even number.")
else:
print(f"{number} is an Odd number.")
Explanation
Calculation: 14 % 2 results in 0.
Condition: The expression 0 == 0 is True.
Action: The program executes the if branch and ignores the else branch.
74
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Explanation
Code Review
75
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
3.3 Boolean Operations
To understand Boolean operations, you must first think of them as the "logic" of a computer. While arithmetic
expressions result in numbers, Boolean expressions result in only one of two values: True or False.
1. Logical Operators
Logical operators allow you to combine multiple comparisons into one complex decision. Python uses three
main operators: and, or, and not.
Use this when multiple conditions must be met simultaneously. Decisions are often based on multiple
conditions. Ex: A program printing if a business is open may check that hour >= 9andhour < 17. Alogical operator
takes condition operand(s) and produces True or False. Python has three logical operators: and, or, and not. The
and operator takes two condition operands and returns True if both conditions are true.
Example: Checking if a person is eligible for a "Senior Discount" (must be over 65 AND have a
membership card).
76
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
B. The or Operator
Use this when you only need one of the conditions to be true. Sometimes a decision
only requires one condition to be true. Ex: If a student is in the band or choir, they will
perform in the spring concert. The or operator takes two condition operands and
returns True if either condition is true.
This is used to check for the opposite of a condition. If the computer is not on, press the power button. The no t
operator takes one condition operand and returns True when the operand is false and returns False when the
operand is true. not is a useful operator that can make a condition more readable and can be used to toggle a
Boolean's value. Ex: is_on = not is_on.
Example:
is_raining = False Output: True
print(not is_raining)
Explanation: not False becomes True. It is often used to say "If NOT empty" or "If
NOT finished."
Logical operators are most powerful when used inside if statements to control the flow of a program.
balance = 500
Output: Withdrawal successful.
withdrawal_amount = 100
account_active = True
Explanation: The computer checks two things: Do you have enough money? AND Is the account open?
Because both are True, the first block of code runs. If you were broke OR the account was closed, it
would jump to the else block.
77
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Order of Precedence
When you mix these together, Python evaluates them in this order:
1. not (Highest)
2. and
3. or (Lowest)
You can combine multiple conditions using Boolean operators:
and: Returns True only if both sides are true.
or: Returns True if at least one side is true.
not: Reverses the value (not True becomes False).
has_key = True
door_unlocked = False
You can enter the room.
if has_key or door_unlocked:
print("You can enter the room.")
Objective: To apply Boolean logic, comparisons, and decision statements in determining eligibility
Code Section
78
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
3.4 Operator Precedence
score = 10
bonus = 2
is_winner = score + bonus > 15 or not score == 0
When a program needs to choose between more than two possible paths, we use the elif (short for "else if")
statement. This allows for chained decisions, where Python checks conditions one by one until it finds a true
one.
If you use separate if statements, the program evaluates every single one independently. This can lead to a
mistake where multiple branches execute accidentally. Using elif ensures that only one branch in the chain is
ever executed.
If we try to curve a test score using separate if blocks, we might accidentally apply two curves to the same
score.
79
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output
score = 60 Output:
Explanation: Because the first if changed the score to 70, it now meets the condition for the second if
statement. Both executed, which was not the programmer's intent.
score = 60 Output:
As mentioned in your text, a travel site can use this logic to handle different layover times.
Example Sample
Output
layover_hours = 0.5 Output:
80
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output
temp = 25
Code Section
81
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output
Code Section
82
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
3.6 Nested Decisions
A nested decision is an if statement located inside another if statement. This is used for complex logic that
requires multiple layers of checking. It occur when you place an if statement inside another if statement. This
allows your program to perform "multi-layered" checks, where a second decision is only made if the first one
passes.
1. Execution Paths
Think of a nested decision like a security checkpoint. You can’t get to the second gate until you have passed
through the first one.
A common real-world example is a login system that first checks if a username exists, and only then checks if
the password is correct.
age = 15
has_student_id = True
Student Discount: $8.00
if age < 18:
# This is the "Nested" block
if has_student_id:
print("Student Discount: $8.00")
else:
print("Minor Rate: $10.00")
else:
print("Standard Rate: $15.00")
Explanation
83
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example : Suppose a programmer is writing a program that reads in a game ID and player count and prints
whether the user has the right number of players for the game
The programmer realizes the code is redundant. What if the programmer could decide the game ID first and
then make a decision about players? Nesting allows a decision statement to be inside another decision
Explanation
If game_over was False, the program would never even look at the current_score. The inner logic is
"protected" by the outer condition.
84
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output
is_weekend = True :
is_sunny = True
Go to the beach!
if is_weekend:
if is_sunny:
print("Go to the beach!")
else:
print("Watch a movie at home.")
A conditional expression (often called the ternary operator) is a "shortcut" in Python. It allows you to write an
entire if-else block in just one single line of code or this is a one-line version of an if-else statement used to
assign a value to a variable based on a condition.
1. The Template
Imagine you are grading a test. If the score is 60 or higher, they pass; otherwise, they fail.
score = 75 score = 75
if score >= 60: result = "Pass" if score >= 60 else "Fail"
result = "Pass" print(result)
else:
result = "Fail"
Explanation: Python checks the middle (score >= 60). Since it is True, it picks the value on the left (Pass).
85
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example B: Calculating a Discount
Explanation: Because 120 > 100 is True, the variable discount is assigned the value 20.
Example C:
age = 18 Output:
status = "Adult" if age >= 18 else "Minor"
Adult
print(status)
Summary
86
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
87
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
88
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: University Enrolment Evaluation System
1. Ask the user for the following information: Enter student name: Ryan
o Student name
Enter entrance exam score: 82
o Entrance exam score
Enter high school GPA: 3.4
o High school GPA
o Interview rating Enter interview rating: 75
2. The program should evaluate the student using
the following rules: Student: Ryan
Enrollment Decision Final Decision: Accepted (Interview Improvement Needed)
o If entrance exam score is 75 or higher:
If GPA is 3.0 or higher:
If interview rating is 80 or higher →
Display "Accepted with Scholarship Recommendation"
Else →
Display "Accepted (Interview Improvement Needed)"
Else →
Display "Accepted on Probation"
o Else →
Display "Not Accepted"
3. Display the student name and the final decision.
Code Section
89
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
CHAPTER IV: Loops
In programming, loops are used to repeat a block of code multiple times. This saves you from writing the same
lines over and over again. A loop is a code block that runs a set of statements while a given condition is true. A
loop is often used for performing a repeating task. Ex: The software on a phone repeatedly checks to see if the
phone is idle. Once the time set by a user is reached, the phone is locked. Loops can also be used for iterating
over lists like student names in a roster, and printing the names one at a time. In this chapter, two types of loops,
for loop and while loop, are introduced.
A while loop is a code construct that runs a set of statements, known as the loop body, while a given condition,
known as the loop expression, is true. At each iteration, once the loop statement is executed, the loop
expression is evaluated again.
• If true, the loop body will execute at least one more time (also called looping or iterating one more time).
• If false, the loop's execution will terminate and the next statement after the loop body will execute.
A while loop runs as long as a specific condition remains True. It is best used when you don't know exactly how
many times you need to repeat.
Basic Format
initialization
while condition:
# code to execute
# increment or update logic
Key Components
To prevent an "infinite loop" (where the program never stops), a while loop typically needs three things:
1. Initialization: A variable set before the loop starts (the starting point).
2. The Condition: A comparison that tells the loop when to keep going.
3. The Update: A line of code inside the loop that changes the variable so the condition eventually
becomes false
count = 1 # 1. Initialization 1
while count <= 5: # 2. Condition 2
print(count) 3
count += 1 # 3. Update (Incrementing count by 1) 4
5
90
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output Explanation
correct_password = "python123" Enter the password: hello We don't know if the user will
user_guess = "" Incorrect! Try again. get it right on the 1st try or the
Enter the password: password 100th try. The loop "polls" the
while user_guess != correct_password: Incorrect! Try again. condition over and over until it
user_guess = input("Enter the password: ") Enter the password: python123 finally becomes False (when
Access Granted! the guess matches).
if user_guess != correct_password:
print("Incorrect! Try again.")
print("Access Granted!")
print("Card Blocked")
91
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Smart Vending Machine Simulation
Objective: To apply loops, nested loops, break, continue, and loop else in solving a real-
world problem.
Sample Output
Instructions Products: 1 2 3 4 5
Enter product number (0 to exit): 2
1. Displays product numbers 1–5.
Dispensing product 2
2. Allows the user to choose a product.
3. Repeats until the user enters 0.
4. If the user enters an invalid number, skip the transaction. Products: 1 2 3 4 5
5. If the user enters product 3, stop the system Enter product number (0 to exit): 7
immediately. Invalid selection.
6. If the user exits normally, display "Thank you for
using the machine." Products: 1 2 3 4 5
Enter product number (0 to exit): 0
1. Thank you for using the machine.
Code Section
92
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
4.2 The for Loop
A for loop is used to iterate over a sequence (like a list, a string, or a range of numbers). It is best used when
you know exactly how many items you need to process. In Python, a container can be a range of numbers,
a string of characters, or a list of values. To access objects within a container, an iterative loop can be
designed to retrieve objects one at a time. A for loop iterates over all elements in a container. Ex: Iterating
over a class roster and printing students' names.
Example
Sample Output Explanation
for i in range(3):
Attempt 0 The range(3) function generates numbers 0,
print(f"Attempt {i}")
Attempt 1 1, and 2. The loop runs once for each
Attempt 2 number.
Example
Sample Output
Explanation
The loop knows exactly how many items are in the list. It starts at the first one, finishes the last one, and then
stops automatically.
A for loop can be used for iteration and counting. The range() function is a common approach for implementing
counting in a for loop. A range()f unction generates a sequence of integers between the two numbers given a
step size. This integer sequence is inclusive of the start and exclusive of the end of the sequence. The range ()
function can take up to three input values.
93
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Examples are provided in the table below.
94
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Comprehensive Discussion & Examples
for i in range(3):
print(f"Counting: {i}")
Using a Custom Start and Stop 2020 This code uses a for loop and the
Sometimes you don't want to start at zero (e.g., printing the 2021 range(2020, 2024) function to
years in a decade). 2022 iterate through a sequence of
2023 numbers starting at 2020 and
for year in range(2020, 2024): ending just before 2024. During
print(year) each iteration, the variable year is
updated to the next value in the
sequence and printed, resulting in
the output of the years 2020,
2021, 2022, and 2023.
Using a Step Value 10 The sequence starts at 10 and
8 subtracts 2 each time. It stops
The "step" determines the gap between numbers. You can 6 before it hits 0.
4
even use a negative step to count backward!
2
for i in range(10, 0, -2):
print(i)
Student 1 present
Attendance Counter Student 2 present
The loop runs once for each
Student 3 present student number.
Student 4 present
for student in range(1, 6): Student 5 present
print("Student", student, "present")
Memory Efficiency: range() does not actually create a list of a million numbers in your computer's
memory. It only calculates the "next" number when the loop asks for it.
Exclusivity: If you need the number 10 to appear in your loop, your stop value must be at least 11.
Step Zero: You cannot have a step of 0. This will result in a ValueError.
95
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
4.3 Nested Loops
A nested loop is a loop inside another loop. The "inner" loop completes all its iterations for every single
"outer" loop iteration. A nested loop has one or more loops within the body of another loop. The two
loops are referred to as outer loop and inner loop. The outer loop controls the number of the inner
loop's full execution. More than one inner loop can exist in a nested loop
96
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Student Score Analyzer
Code Section
97
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
4.4 break and continue
These statements allow you to control the flow of a loop more precisely.
The break statement is used to exit the loop immediately. Once the computer hits a break, it jumps out of the
loop and moves to the very next line of code outside of it.
Real-World Use: You are looking for a specific name in a list of 10,000 people. Once you find the name,
there is no reason to keep looking at the other 9,999 names. You break to save time.
Example Sample Output
names = ["Alice", "Bob", "Charlie", "David"] Checking Alice...
Checking Bob... Found Charlie! Stopping
for name in names: the search.
if name == "Charlie":
Search complete.
print("Found Charlie! Stopping the search.")
break # The loop ends here; "David" is never checked.
print(f"Checking {name}...")
print("Search complete.")
The continue statement is used to skip the rest of the current turn. It does NOT stop the loop; it just tells the
computer, "Stop what you are doing in this specific iteration and jump back to the top for the next one."
Real-World Use: You are printing a list of numbers but you want to skip the "Even" ones.
Example
Sample Output
98
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
4.5 Loop else
The Loop Else clause is one of Python’s most unique and often misunderstood features. Unlike an if-else,
where only one block runs, a loop else is specifically designed to tell you if a loop finished "naturally" or if it
was "forced to stop."
Sample Output
Example
0
for i in range(3): 1
print(i)
2
else:
Done!
print("Done!")
Explanation: If the loop finishes all iterations without being forced to stop, the
else code executes.
The else block attached to a for or while loop follows one simple rule:
It runs if the loop finishes all its iterations (the condition becomes False).
It is skipped if the loop is stopped early by a break statement.
Think of it as: "Run this code only if the loop never hit an emergency stop."
This is the most common use. Imagine you are searching for a specific item in a list. If you find it, you break. If
you look at every single item and never find it, the else block will trigger to let you know.
Sample Output
Example
99
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
B. Implementing with a while Loop (Validation)
You can use else with while to confirm that a process completed its full cycle without interruption.
energy = 3
while energy > 0:
print(f"Working... Energy left: {energy}") Working... Energy left: 3
energy -= 1 Working... Energy left: 2
else: Working... Energy left: 1
# Runs because the loop finished naturally (energy reached 0) Work day finished successfully!
print("Work day finished successfully!")
Without loop else, you would have to create a "Flag" variable (like found = False) to keep track of whether you
hit a break or not. loop else makes your code cleaner and more "Pythonic."
4. Key Takeaways
100
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Secure Access Scanner
Code
101
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
CHAPTER V: Functions
Introduction Functions are the next step toward creating optimized code as a software developer. If the same
block of code is reused repeatedly, a function allows the programmer to write the block of code once, name the
block, and use the code as many times as needed by calling the block by name. Functions can read in values and
return values to perform tasks, including complex calculations. Like branching statements discussed in the
Decisions chapter, functions allow different paths of execution through a program, and th is chapter discusses
control flow and the scope of variables in more detail.
Discussion (6 sentences)
A function is a reusable block of code that performs a specific task. Functions allow programs to be modu lar,
organized, and easier to maintain. By using functions, programmers avoid repetition of code, which reduces
errors and improves readability. Functions make large programs manageable by breaking complex problems
into smaller parts. They also enable collaboration, as different developers can work on separate functions.
Overall, functions improve efficiency, scalability, and clarity of software systems.
102
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output and Explanation
check_balance(1250)
Area of Rectangle
Area: 50
def area(length, width):
return length * width
The function computes the area of a rectangle.
print("Area:", area(10, 5))
# 4. Displaying Output
print(f"Final Amount to Pay: ${final_price:.2f}")
103
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Customer Billing System
Sample Output
Instructions
1. Define a function named calculate_total(price, quantity) Enter Customer Name: Juan Dela Cruz
that computes and returns the total bill. Enter Customer Address: Mandurriao, Iloilo
2. Use input() to collect the following string information:
Enter Product Price: 350
o Customer Name
Enter Quantity: 4
o Customer Address
3. Use input() to collect the following numeric information:
o Product Price (convert to float) ========= CUSTOMER BILL =========
o Quantity Purchased (convert to int) Customer Name: Juan Dela Cruz
4. Call the function to compute the initial total amount. Address: Mandurriao, Iloilo
5. Apply a decision statement: Price: 350.0
o If the total is ₱1,000 or more, apply a 10% Quantity: 4
discount. Original Total: 1400.0
o Otherwise, no discount is applied. Discount: 140.0
6. Display a formatted billing summary that includes: --------------------------------
o Customer Name FINAL AMOUNT: 1260.0
o Address
================================
o Product Price
o Quantity
o Original Total
o Discount
o Final Amount to Pay
Code
104
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
5.2 Control Flow
Discussion
Control flow determines the order in which program statements execute. It allows programs to make decisions,
repeat tasks, and handle different conditions. Common control structures include if, for, while, break, and
return. Without control flow, programs would execute strictly from top to bottom.
Functions rely heavily on control flow to produce meaningful results. Effective control flow leads to correct and
efficient software behavior.
Login Validation
Access Granted
def login(password):
if password == "admin123": The function controls access based on the
print("Access Granted") password.
else:
print("Access Denied")
login("admin123")
Voting Eligibility
Eligible to vote
def check_age(age):
if age >= 18: The function checks the age provided if he/she
print("Eligible to vote") is eligible to vote or not based on the
else: condition.
print("Not eligible")
check_age(20)
105
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output and Explanation
Temperature Alert
High temperature
def temperature(temp):
if temp > 37: The function checks the temperature provided
print("High temperature") and displays corresponding remarks based on
else: the condition High temperature or Normal
print("Normal temperature") temperature.
temperature(38)
def check_number(n):
if n > 0: Negative
print("Positive")
elif n < 0: The function checks the number provided and
print("Negative") displays corresponding remarks based on the
else: condition Positive, Negative or Zero.
print("Zero")
check_number(-5)
106
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Account Status Checker
Objective: Build a program that captures customer details and uses a function to determine the
status of their account balance.
Sample Output
Instructions:
1. Define the Function: Create Enter Customer Full Name: Maria Santos
heck_balance_status(amount) to categorize a balance as Enter Service Address: 789 Highland Ave, Suite 4
"Credit" (Positive), "Debit" (Negative), or "Zero Balance." Enter Current Account Balance: -250.75
2. Collect Professional Inputs: Ask for the Customer Name, ====================================
Service Address, and the Current Balance. OFFICIAL ACCOUNT SUMMARY
3. Process and Display: Call the function and display a ====================================
professional summary.
CLIENT: MARIA SANTOS ADDRESS: 789 Highland
Ave, Suite 4
----------------------------------------------------------
BALANCE: $-250.75
STATUS: Debit Balance (Payment Due)
====================================
Code
107
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
5.3 Variable Scope
Discussion
Variable scope determines where a variable can be accessed in a program. Local variables exist only inside
functions. Global variables exist outside functions and can be accessed anywhere. Understanding scope prevents
accidental data modification. Functions protect data by keeping variables local when possible.
Proper scope management improves program reliability.
Basic Format
How It Works
x = 10 # global
The variable x is a global variable because it is defined outside the function, meaning
def my_function(): it can be accessed and used by any part of the program.
y = 5 # local The variable y is a local variable created inside my_function, which means it only
exists while the function is running and cannot be accessed from the outside.
Python follows a specific hierarchy where it first looks for a variable within the local
scope before searching the global scope to resolve a value.
show()
print("Outside:", x)
108
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Professional Service Fee Calculator
Objective: Develop a program that utilizes global constants and local function logic to calculate a
final service fee including tax and conditional discounts.
Sample Output
Instructions:
1. Define Global Variables: Create a global variable Enter Client Name: Global Tech Solutions
for the TAX_RATE (e.g., 0.12 for 12%).
Enter Client Address: 101 Innovation Way
2. Create a Function: Define
Enter Hourly Rate ($): 85.00
calculate_invoice(client, hourly_rate, hours) that
Enter Total Hours Worked: 45
calculates the subtotal.
3. Apply Logic: Inside the function, apply a 5% --- Overtime Discount Applied to Global Tech Solutions ---
discount added called Overtime Discount
Applied if the hours worked exceed 40. ========================================
4. Handle Scope: Use the global tax rate to OFFICIAL INVOICE
calculate the final total and return a formatted ========================================
summary. CLIENT: Global Tech Solutions
5. User Input: Prompt for the client's name, their ADDRESS: 101 Innovation Way
address, their hourly rate, and the number of TAX RATE: 12.0%
hours worked. ----------------------------------------
TOTAL AMOUNT DUE: $4,069.80
========================================
Code
109
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
5.4 Parameters and Arguments
Parameters are variables listed in a function’s definition that receive values when the function is called.
They allow functions to work with different inputs, making them flexible and reusable. Without parameters,
functions would only perform fixed tasks. Parameters make programs dynamic and adaptable to different
situations. They also improve program design by separating logic from data. Understanding parameters is
essential for building scalable applications.
On the other hand, Keyword arguments allow passing values to function parameters by name.
They make function calls clearer and easier to understand. Order of arguments becomes optional when using
keywords. This feature reduces mistakes in large programs. Keyword arguments improve readability and
maintainability. They are widely used in professional software development.
How It Works
Basic Format of Parameters
Values passed to the function become the parameters.
def function_name(parameter1, parameter2):
The function uses these values during execution.
statements
Different values produce different results.
def function_name(a, b, c): Parameter names are explicitly stated during the call.
statements Python assigns values by matching names.
Order no longer matters.
function_name(a=1, b=2, c=3)
110
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Examples Sample Output and Explanation
def percentage(score, total): The percentage function is defined with two parameters, score and
return (score / total) * 100 total, which are used to calculate and return a value's proportion as a
percentage. In this example, the arguments 45 and 50 are passed into
print("Percentage:", percentage(45, the function, which performs the division and multiplication to return a
50)) final result of 90.0.
Student Record
Ryan BSIT 2
def student(name, course, year):
print(name, course, year) The student function is defined with three parameters intended to display
a student's enrollment details in a specific order. By using keyword
student(course="BSIT", name="Ryan", arguments in the function call, the program correctly matches the data to
year=2) the parameters based on their names rather than their position, allowing
"Ryan" to be assigned to name even though it was passed second.
Travel Booking
Cebu 4 15000
def booking(city, days, budget): The booking function is defined with three parameters to organize travel
print(city, days, budget) information, but the call uses keyword arguments to provide the values in
a non-sequential order. Because each value is explicitly labeled (like
booking(budget=15000, city="Cebu",
city="Cebu"), Python ignores the position of the data and correctly maps
days=4)
each argument to its corresponding parameter.
111
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Hotel Booking System
Objective: Create a program that manages a hotel booking by capturing guest details and
calculating total stay costs using functions and user input.
Sample Output
Instructions:
1. Define the Function: Create Enter Guest Full Name: Juan Dela Cruz
calculate_hotel_bill(nightly_rate, total_nights) to
Enter Guest Home Address: Iloilo City, Philippines
return the product of the two values.
Enter Price per Night (PHP): 2500.50
2. Collect Guest Info: Prompt the user for the Guest
Enter Number of Nights: 4
Name and Address.
3. Collect Booking Details: Ask for the Price Per
Night (as a float) and the Number of Nights (as ========================================
an integer). HOTEL CHECK-OUT SUMMARY
4. Display the Summary: Print a formatted receipt ========================================
showing the guest's information and the GUEST: Juan Dela Cruz
calculated total. ADDRESS: Iloilo City, Philippines
----------------------------------------
STAY: 4 Night(s) @ 2,500.50 per night
TOTAL: PHP 10,002.00
========================================
Code
112
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
5.5 Return Values
A return value is the result sent back by a function after execution. It allows functions to provide computed data
to other parts of the program. Without return values, functions could only display information.
Return values make programs more flexible and powerful. They allow chaining of functions and reuse of
computed results. Most professional programs rely heavily on return values.
Interest: 500.0
Bank Interest
The compute_interest function is defined with a parameter
def compute_interest(balance):
named balance that calculates a 5% interest rate on any
return balance * 0.05
numeric value passed into it. When the function is called with
the argument 10000, it processes the math and returns the
interest = compute_interest(10000)
result to be stored in the interest variable for printing.
print("Interest:", interest)
def fuel_cost(distance, rate): The fuel_cost function defines two parameters, distance
return distance * rate and rate, which act as placeholders for the mathematical
calculation that determines the total fuel expense. By calling the
print("Fuel Cost:", fuel_cost(120, 6)) function with the specific arguments 120 and 6, the program
multiplies these values and immediately prints the resulting cost
of 720.
113
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output and Explanation
# 3. Final Output
print("\n" + "="*45)
print(" OFFICIAL PAYSLIP")
print("="*45)
print(f"EMPLOYEE: {emp_name.upper()}")
print(f"ADDRESS: {emp_address}")
print(f"TAX RATE: {TAX_RATE * 100}%")
print("-" * 45)
print(f"NET PAYABLE AMOUNT: ${final_salary:,.2f}")
print("="*45)
114
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Shipping and Logistics System
Objective: Build a program that calculates the total shipping cost for a customer based on package
weight, distance, and a global fuel surcharge.
Sample Output
Instructions:
1. Global Variable: Define a global variable --- Shipping Details Entry ---
FUEL_SURCHARGE set to 1.05 (representing a 5%
Customer Name: Sarah Miller
increase).
Destination Address: 505 Ocean Drive, Miami
2. Function Definition: Create
Package Weight (lbs): 65
calculate_shipping(weight, distance) where:
3. The base rate is $0.50 per mile. Travel Distance (miles): 150
4. If the package weight is over 50 lbs, add a $20.00 >> Note: Heavy-weight surcharge ($20.00) applied.
heavy-item fee.
5. Math Logic: Multiply the (distance × rate), add =============================================
any heavy-item fees, and finally multiply by the OFFICIAL SHIPPING MANIFEST
FUEL_SURCHARGE. =============================================
6. Inputs: Prompt for Customer Name, Destination CONSIGNEE: SARAH MILLER
Address, Package Weight, and Distance. DESTINATION: 505 Ocean Drive, Miami
7. Output: Display a professional "Shipping ---------------------------------------------
Manifest" with the final cost. WEIGHT: 65.0 lbs | DISTANCE: 150.0 miles
TOTAL SHIPPING FEE: $99.75
=============================================
Code
115
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
CHAPTER VI – Modules
As programs grow longer and more complex, organizing code into separate files called modules becomes
essential.
A module in Python is simply a .py file that contains functions, variables, and executable statements.
Using modules allows programmers to break large programs into smaller, manageable components, improving
readability, maintainability, and collaboration.
Python includes more than 200 built-in modules in its standard library, and hundreds of thousands of third-
party modules are available through the Python Package Index (PyPI).
Understanding how to create, import, and locate modules is a fundamental professional programming skill.
A module is a file that contains Python code which can be reused in other programs. Modules help reduce
repetition and keep large projects well organized. Each module’s name is simply the filename without the .py
extension, and Python treats it as a separate namespace.
Basic Structure
How It Works
File: math_utils.py
def add(a, b): 1. Python loads the module file into memory.
return a + b 2. All functions and variables inside the module become
accessible using the module name.
def multiply(a, b): 3. Code in the module is executed only once when first
return a * b imported
import payroll
116
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Student Grade Utilities Sample Output and Explanation
[Link] Average: 87.67
def average(scores):
return sum(scores) / len(scores)
Grade computation is centralized in one
[Link] module.
import grades
# [Link] - This is your reusable toolkit Enter Land Owner Name: Antonio Cruz
def calculate_land_area(length, width): Enter Property Address: Jaro, Iloilo City
"""Calculates the total square footage of a rectangular Enter Lot Length (ft): 500
lot.""" Enter Lot Width (ft): 600
return length * width
=================================
OFFICIAL LAND AREA REPORT
# [Link] - The user-facing application =================================
import geometry OWNER: Antonio Cruz
LOCATION: Jaro, Iloilo City
# 1. Collecting Customer and Lot Details ----------------------------------------
owner = input("Enter Land Owner Name: ") DIMENSIONS: 500.0ft x 600.0ft
location = input("Enter Property Address: ") TOTAL AREA: 300,000.00 sq. ft.
=================================
# Converting inputs for calculation
l_feet = float(input("Enter Lot Length (ft): ")) The [Link] file serves as a dedicated
w_feet = float(input("Enter Lot Width (ft): ")) module that stores the mathematical
blueprint for area calculations, keeping the
# 2. Using the imported module function main logic clean and reusable.
# Arguments (l_feet, w_feet) are passed to
[Link]'s parameters By using the import statement, the main
total_area = geometry.calculate_land_area(l_feet, program can access these formulas while
w_feet) focusing its own code on gathering specific
customer data like names and addresses.
# 3. Displaying the Professional Output
print("\n" + "="*40) This modular structure allows developers to
print(" OFFICIAL LAND AREA REPORT") update a formula in one single file and have it
print("="*40) instantly improve every program that relies
print(f"OWNER: {[Link]()}") on it across the entire system.
print(f"LOCATION: {location}")
print("-" * 40)
print(f"DIMENSIONS: {l_feet}ft x {w_feet}ft")
print(f"TOTAL AREA: {total_area:,.2f} sq. ft.")
print("="*40)
117
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Real Estate Construction Estimator
Objective: Demonstrate the ability to create a custom Python module, import it into a main script, and
use its functions to perform complex real estate calculations based on user input.
Instructions:
Sample Output
1. Create the Module: Create a file named
[Link]. Inside, define a function --- Construction Estimate System ---
estimate_cost(sq_ft, rate_per_sq_ft) that returns Client Name: Samantha Liam
the total price. Project Type (Residential/Commercial):
2. The Main Script: Create a second file named Commercial
[Link]. Total Area (sq. ft.): 500
3. Import: In [Link], import your engine module. Cost per sq. ft. ($): 340
4. User Input: Prompt the user for the Client Name,
Project Type (e.g., Residential/Commercial), Total ========================================
Square Footage, and Price per Square Foot.
CONSTRUCTION ESTIMATE
5. Function Call: Use the imported function to
========================================
calculate the estimate.
6. Display: Print a professional "Project Estimate" CLIENT: SAMANTHA LIAM
including all details. PROJECT TYPE: Commercial
AREA SIZE: 500.00 sq. ft.
---------------------------------------------
TOTAL ESTIMATED COST: $170,000.00
========================================
*Note: Subject to change based on materials.
Code
118
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
6.2 Importing Names
Discussion
Importing names allows programs to access only the required components of a module.
This makes code cleaner and more readable. It also reduces the risk of name conflicts in large applications.
# 2. Function Call By using import math, you must prefix your commands
# This function returns two values at once with math. (e.g., [Link] or [Link]). This prevents
area_result, circum_result = calculate_circle_details(r_value) confusion if you happened to have your own variable
named "pi" elsewhere in your code.
# 3. Formatted Output
print("\n" + "="*45)
print(f" DESIGN SPECS: {project_name.upper()}") Using [Link] is much more accurate than typing 3.14,
print("="*45) which is vital in engineering and construction where small
print(f"RADIUS: {r_value} m") errors can lead to big structural problems.
print(f"FLOOR AREA: {area_result:.2f} sq. meters")
print(f"PERIMETER: {circum_result:.2f} meters") The math module also gives you access to [Link]() for
print("-" * 45) square roots, [Link]() for rounding up, and
print(f"MATH CONSTANT USED (PI): {[Link]}")
trigonometric functions like [Link]() and [Link]().
print("="*45)
119
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
6.3 Finding and Third-Party Modules (Python Package Index)
Discussion
Many advanced features in Python come from third-party modules. These modules are stored in the Python
Package Index (PyPI) and installed using pip. Using third-party modules greatly expands Python’s capabilities
for data science, web development, AI, and automation.
pip install pandas The command pip install pandas downloads a professional-
import pandas as pd grade data science library that allows Python to handle and analyze
large sets of information with high speed and precision. In the
data = [Link]([10, 20, 30]) script, the [Link] function organizes the list of numbers into a
specialized data structure, while the mean() method instantly
print([Link]()) calculates the mathematical average of those values.
Automation Size(width=1920, height=1080)
120
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Digital Python Joker/Comedian
Objective: Install a third-party module and use it to create a program that generates a random
programming joke for the user.
Instructions:
Sample Output
1. Installation: Open your terminal and type pip
install pyjokes. Welcome to the AI Comedian!
2. Import: In your Python script, use import pyjokes. Press Enter to hear a joke...
3. Function Call: Use the pyjokes.get_joke() function --- YOUR DAILY PROGRAMMER JOKE ---
to get a random joke string. Why do programmers prefer dark mode? Because
4. Display: Create a friendly printout that welcomes light attracts bugs.
the user and tells them the joke. ----------------------------------
Code
121
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
CHAPTER VII - Python Strings
Strings are one of the most fundamental data types in Python. They are used to represent text and are
essential for tasks such as data entry, file handling, user interaction, reporting, and communication between
programs. This chapter explores how strings are created, manipulated, searched, formatted, and combined to
solve real-world problems.
A string is a sequence of characters enclosed in quotes. Python provides many operations for working with
strings, including concatenation, repetition, length calculation, and comparison. These operations allow
programmers to construct messages, process user input, and transform textual data effectively.
String operations are immutable, meaning that every modification produces a new string rather than changing
the original one. This ensures data integrity and predictable behavior when working with text data.
Basic Format
1. Concatenation
Concatenation is the process of joining two or more strings together end-to-end. In Python, this is done using
the plus (+) operator.
Basic Format -
string1 + string2
122
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
2. Repetition
Repetition allows you to create a new string by repeating a specific string a set number of times. This uses the
multiplication (*) operator.
Basic Format
string * n
print(result) # Output: Use case: This is often used for creating visual separators in console
outputs or generating patterns.
# Creating a divider
print("-" * 20)
3. Indexing
Indexing is used to access a single character from a string based on its position. Python uses zero-based
indexing, meaning the first character is at position 0.
Basic Format
string[index]
123
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
4. Length
The len() function is a built-in Python tool that returns the total number of characters in a string, including
spaces, punctuation, and special characters.
Basic Format
len(string)
14
message = "Coding is fun!"
How it works: You pass the string as an argument inside
# Count the characters the parentheses: len(your_string).
message_length = len(message)
Logic: The highest index of a string is always len(string) - 1
print(message_length)
because of the zero-based counting.
This table summarizes the core syntax and behavior of common string operations in Python. It outlines the
specific operator or function used for each action, such as the + for joining strings or len() for counting
characters. Additionally, it provides clear input-to-output examples to illustrate how the result type changes
depending on the operation.
124
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Examples Sample Output and Explanation
result = text1 + " " + text2 Concatenation (+) joins strings together.
length = len(result) The len() function counts the number of characters in a string.
print(result) Because strings are immutable, each operation creates a new
print(length) string in memory.
first_name = "Anna" Welcome, Anna Santos
last_name = "Santos"
full_name = first_name + " " +
last_name The system builds a complete name by concatenating input
values and produces a personalized greeting.
print("Welcome,", full_name)
password = "Secure123" Password Length: 9
print("Password Length:",
len(password)) String length is used to validate whether a password meets
minimum security requirements.
title = "Sales Report" ====================
separator = "=" * 20 Sales Report
print(separator) ====================
print(title) Repetition of a string creates consistent visual markers for
print(separator) console output and reports.
String slicing allows extraction of specific portions of a string using index positions. It enables efficient text
parsing, data extraction, and formatting. Slicing does not modify the original string but returns a new one.
Basic Format
125
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
1. Slice Range
A slice range extracts a "substring" starting from a specific index and ending just before a second index.
Basic Format
string[start:stop]
Basic Format
string[start:stop:step]
3. Omit Indices
Python allows you to leave out parts of the slicing syntax, which triggers useful default behaviors.
Basic Format
string[:stop], string[start:], string[::step]
Hello (Starts at 0)
phrase = "Hello World"
World (Goes to the end)
print(phrase[:5])
HlWl (Every 3rd char from start to end)
print(phrase[6:])
print(phrase[::3])
How it works: * Omitted Start ([:stop]): Defaults to the
beginning of the string (index 0).
Omitted Stop ([start:]): Defaults to the very end of the
string.
Omitted Start/Stop with Step ([::step]): Applies the step to
the entire string.
126
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output and Explanation
127
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity 1 — Order Code Processing System
(String Operations + String Slicing)
Objective: To design a Python program that applies string operations and slicing to process and
analyze structured customer order data.
Instructions
1. Ask the user to enter the following: Sample Output
o Customer Name
o Product Name
o Order Code (format: YYYY-PROD- Enter customer name: Anna
XXX)
Enter product name: Laptop
2. Use string concatenation to create the
Enter order code (YYYY-PROD-XXX): 2025-LAPT-091
customer's full transaction message.
3. Use string slicing to extract:
o Order Year (YYYY) --- Transaction Summary ---
o Product Code (PROD) Customer: Anna
4. Display a formatted transaction summary Product: Laptop
showing: Order Year: 2025
o Customer Name Product Code: LAPT
o Product Name Message: Customer Anna purchased Laptop
o Order Year
o Product Code
o Full Transaction Message
Code
128
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
7.3 Searching and Testing Strings
Discussion
Python provides methods to locate characters, check content, and test conditions within strings. These
functions are crucial for validation, data cleaning, and conditional processing.
Common Methods
The find() method searches for a specific substring within a string and returns the lowest index where it is first
found.
Index of 'is': 7
text = "Python is amazing"
How it works: If the substring exists, it returns the index of the first character.
index = [Link]("is") If the substring is not found, it returns -1.
print(f"Index of 'is': {index}") Explanation: It is useful when you need to know exactly where a piece of text
starts.
The in operator is used to determine if a specific sequence of characters exists anywhere within a nother string.
129
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
3. startswith(): Test Prefix
The startswith() method checks if the string begins with a specific set of characters.
name = "Alice Smith" How it works: It returns True if the string starts with the specified prefix,
otherwise it returns False. It is case-sensitive.
check = [Link]("A") Explanation: This is ideal for filtering data, such as checking if a URL starts
print(f"Starts with 'A'? {check}") with "https" or if a name starts with "A".
The isnumeric() method checks whether all characters in the string are numeric.
Example
Sample Output and Explanation
check = [Link]() How it works: It returns True only if the string contains
print(f"Is '{price}' numeric? {check}") nothing but numbers. If there are spaces, letters, or
punctuation (like a decimal point), it returns False.
# Example with non-numeric character Explanation: This is commonly used to validate user
age = "25 years" input before performing mathematical operations.
print(f"Is '{age}' numeric? {[Link]()}")
130
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
7.4 String Formatting
String formatting inserts values into template strings to create clear, readable output. Python supports several
methods: f-strings (recommended), the format method, and older % formatting. F-strings are concise, evaluate
expressions inside braces, and are generally fastest and most readable for modern code.
Introduced in Python 3.6, f-strings are the most modern, readable, and fastest way to format strings.
This method uses curly braces {} as placeholders within a string and fills them using the .format() function.
last = "Doe" In the first line, the first {} gets first and the second gets last. In
the second line, the values are explicitly mapped to the names
# Using positional and named inside the braces.
placeholders
print("Hello, {} {}".format(first, last)) How it works: You can use empty braces for positional
print("User: {name}, Status: matching, numbers for specific positions, or names for clarity.
{status}".format(name="Admin", Discussion: It is more powerful than older styles because it
status="Active")) allows you to reuse the same variable multiple times without
repeating it in the arguments.
131
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
3. Percent (%) Formatting
This is the "old school" C-style formatting. While still functional, it is generally less recommended in modern
Python.
132
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
# Detailed variables --- F-String Report for SARAH ---
manager = "Sarah" Store ID: 00105
store_id = 105 Monthly Profit: $7,250.35
revenue = 15450.7 Success Rate: 88.4%
expenses = 8200.35 ------------------------------
success_rate = 0.8842 Manager: Sarah | ID: 105
Financials: Rev 15450.7 - Exp 8200.35
# 1. F-strings: Logic and Formatting combined |Left | Center | Right|
# We can do math and use 'flags' for ------------------------------
percentages or comma separators Legacy Log [Sarah]: Store 00105
print(f"--- F-String Report for Final Balance: +7250.35
{[Link]()} ---")
print(f"Store ID: {store_id:05d}") # Adds F-Strings
leading zeros to make it 5 digits F-strings allow for "inline" manipulation. In the example
print(f"Monthly Profit: ${revenue - f"{[Link]()}", we called a string method directly
expenses:,.2f}") # Adds commas and 2 inside the brace. We also used a colon : to trigger
decimals formatting options.
print(f"Success Rate: {success_rate:.1%}") #
Converts 0.8842 to 88.4% :,: This tells Python to add a thousands-separator comma,
print("-" * 30) making numbers like 15000 look like 15,000.
# 2. .format() method: Reusing variables and .1%: This automatically multiplies a decimal by 100 and
Alignment adds the % sign.
# Using numbers {0} allows us to reuse the
same variable multiple times .format() Method (The Flexible Choice)
print("Manager: {0} | ID: {1}".format(manager, The .format() method is excellent for templates. In the line
store_id)) |{:<10}|{:^10}|{:>10}|, the symbols define text alignment:
print("Financials: Rev {rev} - Exp
{exp}".format(rev=revenue, exp=expenses)) <: Left-align within the space.
# Alignment: '<' is left, '>' is right, '^' is center
print("|{:<10}|{:^10}|{:>10}|".format("Left", ^: Center-align within the space.
"Center", "Right"))
print("-" * 30) >: Right-align within the space. The number 10 specifies
the total width of that "column."
# 3. Percent formatting: Precise control and
padding Percent Formatting (The Legacy Precision)
# Useful for creating fixed-width columns in The % style is very specific about types.
older terminal logs
print("Legacy Log [%s]: Store %05d" % %05d: The 0 means "pad with zeros" and the 5 means "up
(manager, store_id)) to five characters total." This is why 105 became 00105.
print("Final Balance: %+.2f" % (revenue -
expenses)) # '+' shows the sign %+.2f: The + is a forced sign flag, ensuring that whether
(positive/negative) the number is positive or negative, a symbol (+ or -) will
always appear.
133
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
7.5 Splitting and Joining Strings
Splitting and joining are essential for converting between strings and lists of substrings. split breaks a string
based on a delimiter (space by default), returning a list. join takes an iterable of strings and concatenates them
using a specified separator, ideal for building CSV lines, sentences, or URLs.
The .split() method breaks a string into a list of smaller strings based on a "separator." When you don't provide
a specific character, it defaults to whitespace.
2. Split by Delimiter
You can tell Python exactly where to cut the string by passing a delimiter (a specific character or substring) into
the .split(",") method.
134
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
3. Join with Separator
The .join() method is the opposite of split(). It takes a list of strings and combines them into one single string,
using a specific separator between them.
Python-is-powerful
word_list = ["Python", "is", "powerful"] Python took the three list items and glued them
# Join them with a hyphen together with the - character in the middle.
hyphenated = "-".join(word_list)
print(hyphenated) How it works: The syntax is "separator".join(list).
Logic: The separator is placed between the elements,
never at the very beginning or the very end.
135
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity 1 — User Registration Validation System
(Searching & Testing Strings + String Formatting + Splitting)
Objective: To create a program that validates user data using string searching, applies string
formatting for professional output, and processes input using splitting techniques.
Instructions
Sample Output
Enter full name: Mark Santos
1. Ask the user to enter:
Enter email address: mark@[Link]
o Full Name
Enter username: marks
o Email Address
Enter hobbies separated by commas: Reading,
o Username
o Hobbies (separated by commas) Coding, Music
2. Validate the email using searching/testing
operations. --- USER PROFILE ---
3. Split the hobbies into a list. Name: Mark Santos
4. Display a formatted user profile using string Username: marks
formatting. Email: mark@[Link]
5. Display the total number of hobbies Hobbies: Reading, Coding, Music
Total Hobbies: 3
--------------------
Code
136
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
CHAPTER VIII — Built-in Data Structures in Python
This chapter introduces Python’s core built-in data structures: Lists, Tuples, Dictionaries, and Sets. These data
structures provide powerful mechanisms for organizing, storing, and manipulating data efficiently.
Understanding when and how to use each structure is essential for designing effective algorithms and real-
world applications. This chapter combines theoretical concepts with hands-on programming practice to ensure
mastery of data handling in Python.
A data structure is a systematic way of organizing, storing, and managing data in a program so that it can be
accessed and modified efficiently.
Rather than working with scattered individual variables, data structures allow programs to handle large
collections of related data as a single unit.
attendance = ["Ana", "John", "Mark", "Liza"] Instead of creating separate variables for each student,
print(attendance) the list stores all names in one organized structure. This
allows easy processing such as adding, removing, or
searching for students.
Customer Account Information Carlos 3500
137
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Examples Sample Output and Explanation
books = {"978-001": "Python Basics", "978- The dictionary enables instant lookup of books by their
002": "Data Science"} ISBN number.
print(books["978-002"])
Structure Purpose
A list is an ordered collection of elements that can be modified after creation. The order
of elements is preserved, and each item can be accessed using its index. Lists support
adding, updating, deleting, and rearranging elements dynamically, making them ideal
for situations where the size and content of the collection may change during program
execution.
Lists are widely used in real-world applications such as shopping carts, task lists, student
records, and transaction logs. Because lists allow duplicate values and maintain insertion
order, they are suitable for sequential data processing.
Example
The list allows dynamic updates: new students are added and existing names are
modified while preserving the order.
138
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Tuple Ordered, fixed sequence
A tuple is similar to a list in that it stores elements in a specific order and allows indexing.
However, tuples are immutable, meaning once created, their contents cannot be
changed. This immutability makes tuples safer for storing critical data that should not
be altered accidentally.
Tuples are commonly used for configuration values, coordinates, database records, and
return values from functions where data integrity is important.
Examples Output
A dictionary stores data as pairs of keys and values, allowing extremely fast access to
information. Instead of searching through a sequence, data is retrieved directly using
its key, resulting in average constant-time performance.
Dictionaries are ideal for databases, configuration systems, contact lists, inventory
management, and user profiles where each piece of data has a unique identifier.
Example
Output
The customer’s information together with balance is retrieved instantly using the key
“customer” and "balance", regardless of dictionary size.
139
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example
Output
contacts = {"Ana": "0912-345-6789", "Ben": "0999-222-3333"}
print(contacts["Ben"]) 0999-222-3333
Dictionary lookups occur in constant time (O(1)), making them ideal for large
databases.
Set Unordered collection of unique items
Sets are widely used in access control, duplicate elimination, data validation, and
recommendation systems.
Example
Output
visitors = ["Ana", "Ben", "Ana", "Carlos"] {'Ana', 'Ben', 'Carlos'}
unique_visitors = set(visitors)
print(unique_visitors)
The set removes duplicate names, ensuring that each visitor is counted only once.
Shopping System ['Laptop', 'Mouse'] {'Laptop': 50000, 'Mouse': 500} (14.5995, 120.9842)
Items: ['Laptop', 'Mouse']
cart = ["Laptop", "Mouse"] Prices: {'Laptop': 50000, 'Mouse': 500}
price = {"Laptop": 50000, "Mouse": 500} Store Location: (14.5995, 120.9842)
purchased = {"Laptop"}
location = (14.5995, 120.9842) A single program uses all four structures to handle different types of
information efficiently.
print(cart, price,location)
print(f"Items: {cart}") This code organizes e-commerce data using various Python
print(f"Prices: {price}") structures: a list for the shopping items, a dictionary for price lookups,
print(f"Store Location: {location}") a set for tracking purchased goods, and a tuple for fixed geographic
coordinates. It then outputs this information to the console, using
both raw variable printing and formatted strings to display the store's
inventory and location details clearly.
140
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
1.4 Choosing the Right Data Structure
Mutability (Change): Do you need to add or remove items later? If yes, use a List or Set. If the data
must remain constant (like GPS coordinates), use a Tuple.
Duplicates: If you need to count every time "Laptop" is added, use a List. If you only care if "Laptop"
exists and want to ignore duplicates, use a Set.
Lookup Speed: This refers to how long the computer takes to find an item. Dictionaries and Sets are
nearly instant ($O(1)$), while Lists and Tuples require scanning every item ($O(n)$).
Memory: Tuples are the "lightest" because they are simple and fixed. Dictionaries are "heavy" because
they store extra information to make lookups fast.
List/Tuple: You walk down the aisle and look at every single book until you find it (O(n)).
Dictionary/Set: You have a magical index that tells you exactly which shelf and position the book is on,
so you go straight to it (O(1)).
141
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Lists (Dynamic Arrays)
Definition of Lists
A list in Python is a built-in data structure used to store an ordered collection of elements. These elements can
be of any data type and may be mixed within the same list. Lists provide a flexible way to organize large
amounts of data under a single variable name, making programs easier to design, read, and maintain.
Lists are ordered, meaning the position of each element is preserved and significant. They are also mutable,
allowing the program to change, insert, or remove elements after the list has been created. This combination
of order and mutability makes lists one of the most frequently used data structures in real-world Python
applications.
Each element in a list is assigned an index starting from zero. Python allows direct access to individual
elements using these indexes. Additionally, slicing enables extracting a range of values from the list,
supporting powerful data manipulation with minimal code.
Unlike arrays in many programming languages, Python lists resize automatically. When elements are added or
removed, the list adjusts its size internally without requiring manual memory management from the
programmer. This behavior makes lists ideal for applications where the amount of data is not known in
advance.
Lists provide powerful built-in operations and methods that allow programmers to manage collections of data
efficiently. Mastery of these operations is essential for developing dynamic, real-world applications.
Creating Lists
Lists are created using square brackets and can store any data type.
Basic Format
Example
The basic syntax for creating a list in Python, which uses square brackets to enclose a collection of items
separated by commas. The example products shows how to store multiple string values in a single variable,
maintaining a specific sequence that can be accessed via indexing. Because lists are mutable, you can easily
update, add, or remove items from this collection as your application's data changes.
List elements are accessed using their index position. Values can be updated directly.
Example
Sample Output and Explanation
144
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example -
Sample Output and Explanation
Example
Sample Output and Explanation
# 3. Updating the inventory with new items User Input: The text in blue (Camera and Webcam)
[Link]([new_item1, new_item2]) represents what you would type while the program
is running.
# 4. Organizing alphabetically for easier tracking
[Link]() Alphabetical Order: Even though "Camera" was
added last, the [Link]() method moved it to
print("\nUpdated Warehouse Inventory:") the front of the list because "C" comes before "K".
print(inventory)
145
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
2.3 Iterating Through Lists
Concept Overview
Iteration is the process of accessing each element in a list one at a time. In Python, iteration is essential for
processing collections of data such as student records, transaction logs, or sensor readings. Python provides
multiple ways to iterate through lists, with for loops and list comprehensions being the most commonly used
and most efficient approaches.
The for loop allows the program to visit each element in the list sequentially.
Basic Format
146
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
List Comprehensions
List comprehensions provide a compact and efficient way to create new lists from existing ones.
Basic Format
prices = [100, 200, 300] The Source: It starts with the prices list containing
discounted = [price * 0.9 for price in prices] three values.
print(discounted)
The Logic: Inside the brackets [ ], the expression
price * 0.9 calculates a 10% discount (keeping 90%
of the original price) for every individual price found
in the prices list.
147
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output and Explanation
# Registering students
The list stores student names in enrollment order.
[Link]("Ana") Adding students with append() is efficient and
[Link]("Ben") supports continuous growth. Removing a student
[Link]("Carlos") requires shifting remaining elements, which is more
[Link]("Diana") costly for large classes but acceptable for moderate
sizes. Membership testing (in) performs a sequential
# Student withdraws search, illustrating why lists are ideal when ordering
[Link]("Ben") and frequent updates are more important than ultra-
fast searching.
# Late enrollee added
[Link]("Evan") This example demonstrates why lists are appropriate
for systems that require ordered, dynamic data
management, such as academic enrollment
# Display class list
platforms, registration portals, and classroom
print("\n--- Current Class List ---") management tools.
for i in range(len(students)):
print(i + 1, students[i])
148
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity Student Sales Performance Analyzer
Objective: Design a Python program that uses list iteration to process multiple student sales
records, compute performance totals, and display a structured report .
Instructions
Sample Output
1. Ask the user how many sales records will be
entered. Enter number of students: 3
2. Use a loop to collect the following information
for each record:
Student 1
o Student Name
Name: Ana
o Daily Sales Amount
3. Store: Sales Amount: 1200
o Names in one list
o Sales amounts in another list Student 2
4. Iterate through the lists to: Name: Ben
o Display each student's sales Sales Amount: 950
o Compute the total sales
o Compute the average sales Student 3
5. Identify and display: Name: Carla
o The highest sale Sales Amount: 1430
o The lowest sale
6. Display a formatted summary report.
--- SALES REPORT ---
Ana : 1200.0
Ben : 950.0
Carla : 1430.0
149
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Tuples (Immutable Sequences)
Definition of Tuples
A tuple is a built-in Python data structure used to store an ordered collection of elements. Similar to lists,
tuples can contain items of any data type and allow indexing and slicing. However, unlike lists, tuples are
immutable, meaning their contents cannot be changed after creation.
Tuples preserve the order of their elements. Each value has a fixed position, but once the tuple is created, its
elements cannot be modified, added, or removed. This immutability ensures stability and prevents accidental
data corruption.
Mutable Yes No
Syntax [] ()
Basic Format
Single-item tuple:
tuple_name = (value1,)
How It Works
When a tuple is created, Python allocates a fixed block of memory for the elements. Because the size and
contents cannot change, Python can optimize memory usage and access speed. Any attempt to modify a tuple
results in an error, which protects the data from accidental changes.
Benefits of Immutability
Because tuples cannot be modified, they protect critical data from accidental changes. Tuples use less memory
and execute faster than lists for fixed data sets.
150
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output and Explanation
record = ("Ana", 85, "Passed") The exam record remains fixed once stored, ensuring data accuracy.
print(record)
Tuple, an immutable data structure used here to group related but
different data types—a name, a score, and a status—into a single fixed
record. Because tuples cannot be changed after creation, they are ideal
for representing "rows" of data where the integrity and order of the
information must remain constant.
Creating Tuples This code demonstrates the syntax for creating tuples, which are
ordered and unchangeable collections. The second example, status =
point = (10, 20) ("Active",), is particularly important because it shows the trailing
comma required by Python to distinguish a single-element tuple from a
Single-element tuple: regular string inside parentheses.
151
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Delivery Information Order: Order#1023
Status: Shipped
delivery = ("Order#1023", Date: 2026-01-10
"Shipped", "2026-01-10")
order_id, status, date = delivery The Tuple: delivery stores three related pieces of information
print("Order:", order_id) (ID, status, and date) as a single immutable unit.
print("Status:", status) The Unpacking: The line order_id, status, date = delivery maps
print("Date:", date) each item in the tuple to its corresponding variable name.
The Output: The print statements then combine descriptive
labels with these variables to create a readable summary.
Only immutable types such as The Tuple Key: Because the coordinates (14.5, 120.9) are in a
tuples can be used as dictionary tuple, they are "locked" and cannot be modified. This allows
keys. Python to calculate a unique "hash" for that key, ensuring it
always points to "Manila."
locations = {(14.5, 120.9): Lists as Keys? If you tried to use a list [14.5, 120.9] as a key,
"Manila"} Python would raise a TypeError because lists are mutable (could
print(locations[(14.5, 120.9)]) change), which would break the dictionary's internal lookup
system.
152
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity — Employee Attendance & Payroll Snapshot System
Objective: Design a Python program that uses tuples to store immutable employee records, applies
tuple packing and unpacking, and generates a formatted payroll report while preserving data
integrity.
Instructions
Sample Output
ID: 1001
Name: Ana
Department: IT
Hours Worked: 40.0
Hourly Rate: 250.0
Total Salary: 10000.0
ID: 1002
Name: Ben
Department: HR
Hours Worked: 38.0
Hourly Rate: 230.0
Total Salary: 8740.0
153
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Dictionaries (Hash Maps)
Definition
A dictionary is a Python built-in data structure that stores information in key–value pairs. Each key maps to a
specific value and allows extremely fast retrieval of data. Dictionaries are mutable, meaning elements can
be added, modified, or removed after creation.
Basic Format
How It Works
dictionary_name = {
key1: value1, Internally, Python dictionaries use a hash table.
key2: value2, When a key is stored, Python converts it into a hash code that determines
key3: value3 where the data is stored in memory. This allows almost instantaneous
} data retrieval.
Key Characteristics
Each key must be unique and immutable, while values may be of any type. Lookup time remains near constant
regardless of dictionary size, which is why dictionaries are widely used in databases, configuration systems,
and caches.
Student Records
students = { John
"2024-001": "Maria",
"2024-002": "John", Student IDs are used as keys to quickly retrieve
"2024-003": "Liza" names. This structure allows schools to manage
} large databases efficiently.
print(students["2024-002"])
Product Pricing System
154
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
4.2 Dictionary Operations and Methods
employee["age"] = 23
print(employee)
Updating Existing Elements
del employee["age"]
print(employee)
Using pop()
[Link]() {}
print(employee)
inventory = {"Pen": 10, "Notebook": 5} {'Pen': 10, 'Notebook': 5, 'Marker': 7}
dict_keys(['Pen', 'Notebook', 'Marker'])
[Link]({"Marker": 7}) dict_values([10, 5, 7])
print(inventory) dict_items([('Pen', 10), ('Notebook', 5), ('Marker', 7)])
Method Purpose
print([Link]()) get() Safely retrieves value
print([Link]())
print([Link]()) keys() Returns all keys
values() Returns all values
items() Returns key-value pairs
update() Adds multiple items
pop() Removes item
clear() Removes all items
del Deletes specific key or entire dictionary
155
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Examples Sample Output and Explanation
156
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output and Explanation
157
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity — Dictionary-Based Inventory Management System
158
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Sets (Unique Collections)
A set in Python is a built-in data structure that stores a collection of unique elements. Unlike lists and tuples,
sets do not maintain any order, meaning the elements have no fixed position and cannot be accessed by index.
Sets are primarily used when the presence or absence of an element is more important than its position.
Because sets automatically eliminate duplicate values, they are ideal for cleaning data and enforcing
uniqueness in applications such as user registration systems, product catalogs, and recommendation engines.
Python supports both mutable sets (set) and immutable sets (frozenset). A normal set can be modified after
creation, allowing elements to be added or removed, while a frozenset cannot be changed once created and is
often used as a dictionary key or for fixed datasets. Internally, sets use a hash-based structure that provides
very fast membership testing. This makes them significantly more efficient than lists when checking if an
element exists in a large collection.
my_set = {1, 2, 3} When an element is added to a set, Python computes its hash value
another_set = set() and stores it in a way that allows the element to be found almost
instantly. If a duplicate value is inserted, the set ignores it
fixed_set = frozenset([4, 5, 6]) automatically. The lack of order allows Python to optimize storage
and searching.
Python provides powerful operations for working with sets, including adding, removing, testing membership,
and performing mathematical set operations. These operations allow programs to compare datasets
efficiently, filter information, and analyze relationships between data groups. Set operations are widely used in
fields such as data science, cybersecurity, and information retrieval.
159
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Set Operations in Python
1. Adding Elements — add()
Conceptual Example:
When a new student registers for an event, their name is added to the registration set. If they try to register
again, the system ignores the duplicate entry.
Conceptual Example:
If a student cancels registration, their name is removed from the registration set.
Using discard() prevents program crashes if the student was never registered.
3. Membership Testing — in
Conceptual Example:
Before granting access to a system, the program checks if a username exists in the authorized users set.
4. Union — |
The union operation combines all elements from two sets while removing duplicates.
It produces a new set that contains every unique element from both original sets.
Conceptual Example:
Combining attendees from two different seminar sessions to create a master attendance list.
5. Intersection — &
The intersection operation returns only the elements that appear in both sets.
It is commonly used to find common memberships, shared permissions, or overlapping datasets.
Conceptual Example:
Finding students who are enrolled in both the math club and science club.
160
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
6. Difference — -
The difference operation returns elements that exist in the first set but not in the second.
This is useful for identifying exclusive memberships or filtering data.
Conceptual Example:
Finding customers who subscribed to Service A but not Service B.
7. Symmetric Difference — ^
The symmetric difference returns elements that appear in either set but not in both.
It highlights elements that are unique to each group.
Conceptual Example:
Identifying students who attended only one of two training sessions.
Together, these operations allow programs to efficiently analyze large collections of data, enforce uniqueness,
and compare datasets with minimal computational cost. This is why sets are widely used in data analytics,
cybersecurity, recommendation systems, and large-scale applications.
Example
Sample Output and Explanation
# Students enrolled in two online courses
Is Ryan enrolled in Python course? True
python_course = {"Ryan", "Anna", "Mark", "Lisa"} All enrolled students: {'Ryan', 'Anna', 'Mark', 'Lisa', 'John', 'Paul'}
data_science_course = {"Mark", "Lisa", "Kevin", "Paul"} Students in both courses: {'Mark', 'Lisa'}
Only Python course: {'Ryan', 'Anna', 'John'}
# Add a new student Only Data Science course: {'Paul'}
python_course.add("John") Enrolled in only one course: {'Ryan', 'Anna', 'John', 'Paul'}
# Remove a student This program models a real enrollment system where sets
data_science_course.discard("Kevin")
ensure that each student appears only once per course.
Set operations are used to analyze shared enrollments,
# Membership test
print("Is Ryan enrolled in Python course?", "Ryan" in exclusive memberships, and the complete student
python_course) population efficiently.
# Set operations
print("All enrolled students:", python_course |
data_science_course)
print("Students in both courses:", python_course &
data_science_course)
print("Only Python course:", python_course -
data_science_course)
print("Only Data Science course:", data_science_course -
python_course)
print("Enrolled in only one course:", python_course ^
data_science_course)
161
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Examples Sample Output and Explanation
A = {1, 2, 3} True
B = {3, 4, 5} {1, 3, 6}
{1, 3, 4, 5, 6}
[Link](6) {3}
[Link](2) {1, 6}
{1, 4, 5, 6}
print(3 in A)
print(A) Modifying: A starts as {1, 2, 3}, but after adding 6
print(A | B) # Union and removing 2, it becomes {1, 3, 6}.
print(A & B) # Intersection Membership: 3 in A returns True because 3 is still
print(A - B) # Difference present in the set.
Mathematical Operations:
Union (A | B): Combines all unique items
from both sets: {1, 3, 4, 5, 6}.
Intersection (A & B): Finds only the items
common to both: {3}.
Difference (A - B): Returns items in A that
are not in B: {1, 6}.
162
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Examples Sample Output and Explanation
science_club = {"Anna", "Mark", "John", "Lisa"} Students in both clubs: {'John', 'Lisa'}
math_club = {"John", "Lisa", "Paul"} All club members: {'Anna', 'Mark', 'John', 'Lisa',
'Paul'}
print("Students in both clubs:", science_club & Only Science Club: {'Anna', 'Mark'}
math_club)
print("All club members:", science_club | The intersection operation identifies students
math_club) enrolled in both clubs, while the union produces a
print("Only Science Club:", science_club - complete list of all participants. The difference
math_club) operation reveals students who belong exclusively to
the Science Club.
163
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity — Event Registration Management Using Sets
• Apply Python sets to manage unique data === Event Registration System ===
• Perform set operations to analyze information Enter choice: 1
• Implement membership testing and element
Enter participant name: Anna
management
Enter session (M/A): M
• Build a functional real-world program using sets
Participant registered.
Problem Scenario
Enter choice: 1
You are tasked with developing an Event Registration Enter participant name: Mark
System for a university seminar. Enter session (M/A): A
Each participant can register only once. The system must Participant registered.
also compare two event sessions to identify overlapping
and unique participants.
Enter choice: 5
Instructions
All Participants: {'Anna', 'Mark'}
1. Create two sets: morning_session and Both Sessions: set()
afternoon_session. Morning Only: {'Anna'}
2. Display a menu with the following options: Afternoon Only: {'Mark'}
o 1 — Register Participant
o 2 — Remove Participant Enter choice: 3
o 3 — Check Registration Enter name to check: Anna
o 4 — View All Registrations Participant is registered.
o 5 — Compare Sessions
o 6 — Exit Enter choice: 6
3. Use add() and remove() to manage registrations. System closed.
4. Use membership testing (in) to check if a
participant is registered.
5. Use set operations (union, intersection,
difference, symmetric difference) in the
comparison feature.
6. Continue running until the user selects Exit.
164
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Section 6 — Comparing Data Structures
Lists and tuples are both ordered sequences, but they differ significantly in behavior and purpose.
A list is mutable, meaning its contents can be changed after creation, making it suitable for dynamic data such
as shopping carts or task lists.
A tuple is immutable, which means its contents cannot be modified, making it ideal for fixed records such as
coordinates or configuration settings.
Example
Lists allow modification (append, remove), while tuples protect data from accidental change.
Dictionaries store key–value pairs, whereas sets store only unique values.
Use dictionaries when data needs a label or identifier (e.g., username → password).
Use sets when the goal is to ensure uniqueness and perform comparisons.
Example
Choosing the right structure improves program clarity, speed, and reliability.
Ordered data → List or Tuple
Key-value relationships → Dictionary
Unique collections → Set
165
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Section 7 — Practical Applications and Case Studies
Uses lists for records, dictionaries for indexing, and sets for uniqueness validation.
Example: Customer database combining ID lookup (dictionary), list of transactions, and set of registered
emails.
Sample Output and Explanation
Example
customers = {"C001": "Anna", "C002": "Mark"} Customers: {'C001': 'Anna', 'C002': 'Mark'}
transactions = []
registered_emails = set() Transactions: ['C001 bought Laptop', 'C002 bought Phone']
Uses dictionaries for student profiles, lists for enrolled courses, and sets to prevent duplicate registrations.
students = {
Students: {'2024-001': {'name': 'Anna', 'courses': ['Math',
"2024-001": {"name": "Anna", "courses": ["Math",
'English']}, '2024-002': {'name': 'Mark', 'courses':
"English"]},
['Science']}}
"2024-002": {"name": "Mark", "courses":
["Science"]} Registered IDs: {'2024-002', '2024-001'}
}
registered_ids = set([Link]())
Dictionaries store detailed profiles, lists manage
print("Students:", students) enrolled subjects, and sets prevent duplicate student
IDs.
print("Registered IDs:", registered_ids)
166
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
7.3 Inventory Control Application
Uses dictionaries for product–quantity mapping, lists for order processing, and sets for supplier validation.
inventory = {"Laptop": 10, "Phone": 25} Inventory: {'Laptop': 10, 'Phone': 25}
orders = [] Orders: ['Anna ordered Laptop', 'Mark ordered Phone']
suppliers = {"TechCorp", "DeviceHub"} Suppliers: {'DeviceHub', 'TechCorp'}
[Link]("Anna ordered Laptop")
The dictionary tracks stock levels, the list records customer
[Link]("Mark ordered Phone")
orders, and the set ensures each supplier appears only once.
print("Inventory:", inventory)
print("Orders:", orders)
print("Suppliers:", suppliers)
Uses sets for friend recommendations, dictionaries for profiles, and lists for activity feeds.
profiles = {
"anna": {"name": "Anna", "age": 20}, Profiles: {'anna': {'name': 'Anna', 'age': 20}, 'mark': {'name':
"mark": {"name": "Mark", "age": 21} 'Mark', 'age': 21}}
} Current Friends: ['mark']
Friend Suggestions: {'john', 'lisa', 'mark'}
friend_list = ["mark"]
friend_suggestions = {"john", "lisa", "mark"} Dictionaries store user profiles, lists maintain friend order, and
sets generate unique friend suggestions.
print("Profiles:", profiles)
print("Current Friends:", friend_list)
print("Friend Suggestions:", friend_suggestions)
167
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity — Python Built-in Data Structures
Campus Management Data System
Objective: Students will be able to Use lists to manage dynamic collections of data, use tuples to
store fixed and protected information, use dictionaries to organize structured records, use sets to prevent
duplicate data and combine multiple data structures in one working program.
Problem Scenario
Sample Output
A college registrar needs a simple system to
manage student information: Enter Student ID: 2025-019
Code
168
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
CHAPTER IX — Sorting and Searching Algorithms in Python
Sorting and searching are among the most important algorithmic concepts in computer science and practical
programming. They allow programs to efficiently organize large volumes of data and retrieve specific
information quickly and accurately. Without these algorithms, many modern systems such as databases,
financial software, search engines, and management systems would be extremely slow and unreliable. This
chapter equips students with foundational knowledge of how these algorithms work and how to implement
them effectively in Python.
Learning Objectives
By the end of this chapter, students should be able to:
Understand the purpose and importance of sorting and searching algorithms.
Implement multiple sorting algorithms in Python.
Implement linear and binary search algorithms.
Evaluate algorithm efficiency using time complexity.
Apply sorting and searching techniques in real-world applications.
Sorting is the process of arranging data elements into a specific sequence, such as ascending or descending
order. Proper sorting improves readability, simplifies analysis, and dramatically speeds up searching
operations. Searching refers to locating a particular item within a collection of data. Together, sorting and
searching form the backbone of most data-driven applications, enabling software systems to process and
retrieve information efficiently.
# Outer loop to traverse through all list elements Step-by-Step Execution Trace
for i in range(len(data)): Using the input: data = [5, 2, 8, 1]
# Inner loop for comparisons; -i avoids already ]
sorted elements Pass 1 (i = 0)
# -1 avoids 'out of bounds' error when checking The inner loop runs from j = 0 to 2 (because 4 - 0 - 1
j+1 = 3 iterations).
for j in range(len(data) - i - 1): 1. Compare index 0 and 1: Is 5 > 2? Yes.
# Compare adjacent elements o Swap: [2, 5, 8, 1]
if data[j] > data[j+1]: 2. Compare index 1 and 2: Is 5 > 8? No.
# Swap if the element on the left is greater o No change: [2, 5, 8, 1]
than the right 3. Compare index 2 and 3: Is 8 > 1? Yes.
data[j], data[j+1] = data[j+1], data[j] o Swap: [2, 5, 1, 8]
Result: The largest number (8) has
print(f"Sorted data: {data}") "bubbled" to its correct position at the end.
Pass 2 (i = 1)
The inner loop runs from j = 0 to 1 (because 4 - 1 - 1
= 2 iterations).
1. Compare index 0 and 1: Is 2 > 5? No.
o No change: [2, 5, 1, 8]
2. Compare index 1 and 2: Is 5 > 1? Yes.
o Swap: [2, 1, 5, 8]
Result: The next largest number (5) is now in
its correct place.
Pass 3 (i = 2)
The inner loop runs only for j = 0 (because 4 - 2 - 1 =
1 iteration).
1. Compare index 0 and 1: Is 2 > 1? Yes.
o Swap: [1, 2, 5, 8]
Result: The list is now fully sorted.
Pass 4 (i = 3)
The inner loop range becomes 0 (4 - 3 - 1 = 0). The
loop finishes and the algorithm terminates.
sales = [320, 150, 450, 200, 275] Sorted Sales: [150, 200, 275, 320, 450]
170
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
9.2.2 Selection Sort
Selection Sort organizes data by repeatedly selecting the smallest remaining element and placing it at the correct
position in the list. Unlike Bubble Sort, it makes fewer swaps, which can be advantageous in situations where
writing to memory is expensive. However, its overall time complexity remains quadratic, making it unsuitable
for very large datasets. Selection Sort provides a clear conceptual model of how sorting by selection works.
Basic Format
for i in range(len(data)):
min_index = i
for j in range(i+1, len(data)):
if data[j] < data[min_index]:
min_index = j
data[i], data[min_index] = data[min_index],
data[i]
How It Works
The Outer Loop (for i in range(len(data))): This loop defines the current position that needs to be filled with the correct
sorted value. Everything to the left of i is already sorted. After each full pass of the outer loop, the smallest remaining
value is placed at index i.
The Initial Assumption (min_index = i): At the start of each pass, we assume the element at the current position i is the
smallest value in the unsorted portion. We store its index in min_index to track it.
The Inner Loop (for j in range(i+1, len(data))): This loop searches through the remaining unsorted part of the list to
find the actual minimum value.
The term i+1: We start searching from the element immediately after i, since everything before i is already
sorted and finalized.
The Comparison (if data[j] < data[min_index]): If we find an element smaller than our current "minimum," we
update min_index to the new position j.
The Swap (data[i], data[min_index] = data[min_index], data[i]): Once the inner loop finishes scanning, we have found
the true minimum of the unsorted section. We swap it with the element at index i. Unlike Bubble Sort, which swaps
many times, Selection Sort performs only one swap per outer loop pass.
171
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Sample Output and Explanation
Examples
prices = [1200, 450, 800, 300, 1500] Sorted Prices: [300, 450, 800, 1200, 1500]
Pass 1 (i = 0):
for i in range(len(prices)): Starts with 1200. The inner loop finds that
min_index = i 300 (at index 3) is the smallest.
Swap 1200 and 300 [300, 450, 800, 1200,
for j in range(i+1, len(prices)):
1500]
if prices[j] < prices[min_index]:
Pass 2 (i = 1):
min_index = j Starts with 450. The inner loop looks at 800,
prices[i], prices[min_index] = prices[min_index], 1200, 1500 and finds nothing smaller than
prices[i] 450.
No Swap needed [300, 450, 800, 1200,
print("Sorted Prices:", prices) 1500]
Pass 3 (i = 2):
Starts with 800. The inner loop looks at
1200, 1500. Nothing is smaller than 800.
No Swap needed [300, 450, 800, 1200,
1500]
Pass 4 (i = 3):
Starts with 1200. The inner loop looks at
1500. Nothing is smaller than 1200.
No Swap needed.
data = [64, 25, 12, 22, 11] Sorted [11, 12, 22, 25, 64]
Pass 1 (i = 0):
for i in range(len(data)): Find the minimum in [64, 25, 12, 22, 11]. The
min_idx = i minimum is 11.
Swap 11 with the first element (64).
for j in range(i + 1, len(data)):
Result: [11, 25, 12, 22, 64]
if data[j] < data[min_idx]: Pass 2 (i = 1):
min_idx = j Find the minimum in the unsorted part [25,
# Swap the found minimum element with the first 12, 22, 64]. The minimum is 12.
element Swap 12 with the first unsorted element
data[i], data[min_idx] = data[min_idx], data[i] (25).
Result: [11, 12, 25, 22, 64]
print("Sorted:", data) Pass 3 (i = 2):
Find the minimum in the unsorted part [25,
22, 64]. The minimum is 22.
Swap 22 with the first unsorted element
(25).
Result: [11, 12, 22, 25, 64]
Pass 4 (i = 3):
Find the minimum in the unsorted part [25,
64]. The minimum is 25.
Since 25 is already at the start of the
unsorted part, no actual change occurs.
Result: [11, 12, 22, 25, 64]
Pass 5 (i = 4):
Only [64] remains. By default, it is in the
correct position.
Result: [11, 12, 22, 25, 64]
172
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity — Sorting Algorithms (Bubble Sort / Selection Sort)
Student Grade Sorting System
Objective To develop a Python program that collects student records, applies a sorting algorithm
(Bubble Sort or Selection Sort), and displays the sorted results. This activity strengthens understanding of
algorithmic thinking, data manipulation, and real-world application of sorting techniques.
Instructions
Sample Output
1. Create an empty list to store student records. Enter number of students: 3
2. Ask the user how many students will be entered.
3. For each student, collect the following information:
Student 1
o Student Name
Name: Ana
o Student ID
o Final Grade (integer) ID: S101
4. Store each student record as a dictionary inside the list. Final Grade: 88
5. Implement either Bubble Sort or Selection Sort to sort the
students by grade in ascending order. Student 2
6. Display the sorted student records in a formatted report. Name: Ben
ID: S102
Final Grade: 75
Student 3
Name: Cara
ID: S103
Final Grade: 92
173
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
9.3 — Searching Algorithms
Linear Search is the most straightforward searching technique. It checks each element in the list sequentially
until the target value is found or the list ends. While simple to implement, its performance decreases
significantly as the dataset grows. Linear Search is best suited for small datasets or unsorted data where more
advanced searching techniques cannot be applied.
Basic Format
How It Works
The Loop (for item in data:): This is the "traversal" phase. The program starts at the very first element of
the list and moves through every single item, one by one, in order.
The Comparison (if item == target:): Inside the loop, the program performs a check. It compares the
current item it is looking at against the target value you are searching for.
The Flag (found = True): If a match is found, it updates a Boolean variable (usually called a "flag") to True.
This serves as a permanent record that the item exists somewhere in the list.
174
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Examples Sample Output and Explanation
175
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
9.3.2 Binary Search
Binary Search is a highly efficient searching algorithm that works only on sorted data. Instead of checking each
element, it repeatedly divides the search range in half, drastically reducing the number of comparisons. This
makes Binary Search extremely fast for large datasets. Many real-world systems, such as databases and file
systems, rely on this principle for rapid data retrieval.
Basic Format
How It Works
In a list, low is the index of the first item and high is the
index of the last item in the area you are searching.
scores = [55, 65, 70, 80, 90, Score Found: True Iteration 2
95] Initial Setup 1. Calculate Mid: mid = (3 + 5) // 2 which is 4.
target = 80 Data: [55, 65, 70, 80, 90, 2. Check Value: scores[4] is 90.
95] 3. Compare: Is 90 == 80? No.
low = 0 Indices: 0, 1, 2, 3, 4, 5 4. Decide: Is 90 < 80? No (It's higher).
5. Action: Since 90 is too high, the target must be
high = len(scores) - 1 Target: 80
on the left. We move the high pointer to mid -
found = False Pointers: low = 0, high = 5 o New Range: low = 3, high = 3.
Iteration 3
Step-by-Step Execution
while low <= high: 1. Calculate Mid: mid = (3 + 3) // 2 which is 3.
Iteration 1
mid = (low + high) // 2 2. Check Value: scores[3] is 80.
1. Calculate Mid: mid = (0 + 5)
if scores[mid] == target: 3. Compare: Is 80 == 80? Yes!
// 2 which is 2.
found = True 2. Check Value: scores[2] is
break 70. Action: Set found = True and break the loop
elif scores[mid] < target: 3. Compare: Is 70 == 80? No.
low = mid + 1 4. Decide: Is 70 < 80? Yes.
else: Action: Since 70 is too low,
high = mid - 1 the target must be on the
right. We move the low
pointer to mid + 1
print("Score Found:", found)
New Range: low = 3, high = 5.
176
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Examples Sample Output and Explanation
A teacher wants to check if a specific score exists Enter a grade to search for: 91
in a sorted list of student grades. Grade in system: True
grades = [45, 52, 68, 77, 84, 91, 98]
target = int(input("Enter a grade to search for: ")) Initial Range: low is 0, high is 6.
First Mid: (0 + 6) // 2 = 3. grades[3] is 77.
low = 0
high = len(grades) - 1 Comparison: 77 is less than 91. The target must be to the right.
found = False
New Range: low becomes mid + 1 (4). high remains 6.
while low <= high: Second Mid: (4 + 6) // 2 = 5. grades[5] is 91.
mid = (low + high) // 2
Match: 91 matches the target! found becomes True.
if grades[mid] == target:
found = True
break
elif grades[mid] < target:
low = mid + 1
else:
high = mid - 1
if found:
print(f"Product {target} is in stock.")
else:
print(f"Product {target} not found.")
177
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity — Searching & Sorting System
Objective: To design and implement a Python program that stores student records, allows the user to choose
a sorting algorithm (Bubble Sort or Selection Sort), sorts the data accordingly, and performs search operations
on the sorted dataset.
Sample Output
Instructions
Student Found:
S102 - Ana - Grade: 88
178
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Programming Activity Grading Rubric
References
1. Cormen, T. H., Leiserson, C. E., Rivest, R. L., & Stein, C. (2022). Introduction to algorithms (4th ed.). MIT
Press.
2. Downey, A. B. (2016). Think Python: How to think like a computer scientist (2nd ed.). O’Reilly Media.
[Link]
3. Lutz, M. (2013). Learning Python (5th ed.). O’Reilly Media.
4. Miller, B. N., & Ranum, D. L. (2014). Problem solving with algorithms and data structures using Python.
Franklin, Beedle & Associates.
5. Python Software Foundation. (2024). Python documentation. [Link]
6. GeeksforGeeks. (n.d.). Data structures and algorithms in Python. [Link]
structures/
7. Real Python. (n.d.). Python tutorials. [Link]
179
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus