[Go to site: main page, start]

0% found this document useful (0 votes)
23 views191 pages

Learning Module in Python Programming

The Programming with Python Course offers a comprehensive introduction to Python, covering its history, syntax, and fundamental programming concepts. Students will learn through hands-on activities, focusing on problem-solving, data manipulation, and practical applications across various domains. By the end of the course, participants will be equipped to design and debug Python programs effectively.

Uploaded by

ykwlibs
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views191 pages

Learning Module in Python Programming

The Programming with Python Course offers a comprehensive introduction to Python, covering its history, syntax, and fundamental programming concepts. Students will learn through hands-on activities, focusing on problem-solving, data manipulation, and practical applications across various domains. By the end of the course, participants will be equipped to design and debug Python programs effectively.

Uploaded by

ykwlibs
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Welcome to the Programming with Python Course

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.

See you in class!

Prof. Ryan M. Agsaluna


COT Faculty
Introduction

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

Chapter 1: Python Fundamentals and Program Structure

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:

 Explain Python’s origin, features, and applications


 Install and configure a Python development environment
 Write and execute basic Python programs
 Apply correct syntax and program structure

Topics Covered:

 Background and history of Python


 Core characteristics and key features
 Popular use cases, advantages, and disadvantages
 Getting started with Python
 Writing the "Hello World" program
 Basic syntax and indentation rules
 Introduction to variables and input/output

Activities:

 Individual: Install Python and an IDE


 Individual: Write and run basic programs
 Group: Discuss real-world applications of Python
Chapter 2: Expressions, Variables, and Data Handling

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:

 Construct and evaluate expressions


 Perform type conversion
 Use variables properly
 Implement formatted input and output

Topics Covered:

 Expressions and operators


 Input and output operations
 print() function and formatting (sep, end)
 Variable assignment and naming conventions
 Constants and memory concepts
 Type conversion

Activities:

 Individual: Write programs using formatted output


 Individual: Create programs that use input and variables
 Group: Develop a simple data processing system

Chapter 3: Control Structures

Duration: 2 Weeks

Overview:
This chapter introduces program decision-making using conditional statements and logical operations.

Learning Objectives:
Students will be able to:

 Use Boolean expressions


 Apply comparison and logical operators
 Implement conditional statements
 Design nested decision structures
Topics Covered:

 Boolean values
 Comparison and logical operators
 if, if-else, elif statements
 Nested decisions
 Conditional expressions

Activities:

 Individual: Solve decision-based programming tasks


 Group: Develop a rule-based program

Chapter 4: Loops and Repetition

Duration: 2 Weeks

Overview:
This chapter focuses on iterative programming using loops and control statements.

Learning Objectives:
Students will be able to:

 Implement while and for loops


 Construct nested loops
 Control program flow using break and continue
 Apply loop logic to real-world problems

Topics Covered:

 While loop
 For loop
 Nested loops
 Break and continue
 For–else statement

Activities:

 Individual: Create repetition-based programs


 Group: Design a loop-driven system
II. Final

Chapter 5: Functions and Modular Programming

Duration: 2 Weeks

Overview:
Students learn how to build reusable and organized programs using functions.

Learning Objectives:
Students will be able to:

 Define and call functions


 Use parameters and return values
 Apply functions to solve practical problems

Topics Covered:

 Defining functions
 Function parameters and return values
 Practical applications (ATM system, calculators, billing systems)

Activities:

 Individual: Develop programs using functions


 Group: Build a function-based application

Chapter 6: Python Modules and Libraries

Duration: 2 Weeks

Overview:
This chapter introduces Python’s modular system and external libraries.

Learning Objectives:
Students will be able to:

 Import and use Python modules


 Install external packages
 Apply libraries to automation and data processing
Topics Covered:

 Using built-in modules


 Installing external modules (pip)
 Libraries for automation, data analysis, and web tasks

Activities:

 Individual: Create programs using Python modules


 Group: Develop a module-driven project

Chapter 7: Strings and Text Processing

Duration: 2 Weeks

Overview:
This chapter covers advanced text processing using Python string operations.

Learning Objectives:
Students will be able to:

 Manipulate strings efficiently


 Apply advanced string formatting
 Validate and process textual data

Topics Covered:

 String operations and concatenation


 String formatting techniques
 String searching and testing
 Splitting and joining strings

Activities:

 Individual: Build text-processing programs


 Group: Design a validation system
Chapter 8: Built-in Data Structures

Duration: 2 Weeks

Overview:
Students explore Python’s core data structures for efficient data management.

Learning Objectives:
Students will be able to:

 Use lists, tuples, dictionaries, and sets


 Perform data storage and retrieval operations
 Choose appropriate data structures for specific problems

Topics Covered:

 Lists and tuples


 Dictionaries
 Sets
 Data structure operations and iteration

Activities:

 Individual: Implement data-driven programs


 Group: Develop a data management system

Chapter 9: Sorting, Searching, and Final Project

Duration: 2 Weeks

Overview:
This final chapter integrates algorithmic problem solving with project development.

Learning Objectives:
Students will be able to:

 Implement sorting and searching algorithms


 Analyze algorithm efficiency
 Develop and present a complete Python application

Topics Covered:

 Sorting algorithms (Bubble Sort)


 Searching algorithms (Linear and Binary Search)
 Time complexity
 Final project development, testing, and presentation

Activities:

 Group: Final project development


 Group: Testing, debugging, and presentation

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

CHAPTER I: Python Statements 1


1- Background and History of Python 1
1-2- Core Characteristics and Key Features 1–2
1-3- Popular Use Cases, Advantages, and Disadvantages 2
1-4- Getting Started 4
1-5- The "Hello World" Example and Basic Syntax 5
1-6- Variables and Input/Output Introduction 5–6
1-7- 1.2 Input/Output 7
1-8- Basic Output and the print() Function 7
1-9- The sep (Separator) and end Arguments 8
1-10- Graded Activity: Output Formatting 10
1-11- Basic Input Concepts and Variable Storage 11–12
1-12- Variables: Assignment and Naming Conventions 13–16
1-13- Constants and Real-World Variable Applications 17
1-14- Graded Activity: Student Information Using Input
and Variables 18

CHAPTER II: Understanding Python Expressions 35


2-1- What is an Expression? 35
2-2- The Building Blocks of Expressions 35
2-3- The Python Shell (Interactive Mode) 36
2-4- Real-World Example: Membership Duration System 36–37
2-5- Type Conversion 38
2-6- Graded Activity: Daily Allowance Tracker 37–38

CHAPTER III: Control Structures 68


3-1- Boolean Values 68–69
3-2- Comparison and Logical Operators 69–72
3-3- Decision Statements (if, if–else, elif) 72–85
3-4- Nested Decisions 85–90
3-5- Conditional Expressions 90–92

CHAPTER IV: Loops 93


4-1- While Loop 93–95
4-2- For Loop 95–97
4-3- Nested Loops 96–97
4-4- Break and Continue 98–100
4-5- For–Else Statement 100–101
4-6- Graded Activity: Student Score Analyzer 97
4-7- Graded Activity: Secure Access Scanner 101–102
TABLE OF CONTENTS

TOPIC Page

CHAPTER V: Functions 102


5-1- Defining Functions & Benefits of a Function 102–103
5-2- Function Parameters and Return Values 103–106
5-3- Practical Examples: ATM Balance Check,
Area Calculator, Discount System 103–106

CHAPTER VI: Modules 118


6-1- Installing and Using Modules 118–120
6-2- Web Requests, Data Analysis, Automation Examples 119–121
6-3- How Modules Work (pip, import) 120
6-4- Graded Activity: Digital Python Joker / Comedian 121–122

CHAPTER VII: Python Strings 122


7-1- String Operations and Concatenation 122–124
7-2- String Formatting (f-strings, format, %) 124–133
7-3- Advanced Formatting Templates 133
7-4- String Searching and Testing 133–135
7-5- Splitting and Joining Strings 134–135
7-6- Graded Activity: User Registration Validation System 136–137

CHAPTER VIII: Built-in Data Structures 137


8-1- Definition and Importance of Data Structures 137–138
8-2- Lists: Concepts, Indexing, Mutability 138–148
8-3- Modifying and Iterating Through Lists 148–150
8-4- Tuples: Immutable Records and Access 150–152
8-5- Dictionaries: Hash Maps and Iteration 153–160
8-6- Sets: Unique Collections and Operations 161–167
8-7- Graded Activity: Campus Management Data System 168

CHAPTER IX: Sorting and Searching Algorithms 169


9-1- Concepts and Importance of Sorting and Searching 169
9-2- Bubble Sort Algorithm 170–172
9-3- Linear Search Algorithm 172–174
9-4- Binary Search Algorithm 174–175
9-5- Algorithm Efficiency and Time Complexity 175
9-6- Programming Activity Grading Rubric 179
References 179
CHAPTER I: Python Statements

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

Python is a high-level, interpreted, and general-purpose programming


language that has become one of the most popular in the world. It was
created by Guido van Rossum and first released in 1991. Its design
philosophy emphasizes code readability, famously using significant
indentation rather than curly braces to define code blocks.

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.

Category Description Popular Libraries/Frameworks

Analyzing data, building neural networks, and NumPy, Pandas, TensorFlow,


Data Science & AI
automation. PyTorch

Web Development Building the "back-end" (server-side) of websites. Django, Flask, FastAPI

Writing scripts to automate repetitive tasks (e.g., file


Automation Selenium, Beautiful Soup
renaming).

Scientific Used by researchers for complex math and physics


SciPy, Matplotlib
Computing simulations.

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.

2. Why is Python so Popular?

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.

3. Major Use Cases

Python is the "Swiss Army Knife" of programming. It is used across nearly every industry:

A. Data Science and Machine Learning

This is Python's biggest playground. It is the industry standard for AI.


 Libraries: Pandas (data analysis), NumPy (math), Scikit-learn (Machine
Learning).
 Example: Predicting stock market trends or Netflix's recommendation
engine.

B. Web Development (Back-end)

Python handles the "brains" behind websites.

 Frameworks: Django (for large, secure sites like Instagram) and Flask
(for smaller, flexible apps).

C. Automation and Scripting

If you have a boring, repetitive task, Python can do it for you.

 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

Scientists use Python for complex simulations.

 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

Category Top Tool/Library Famous User

Data Science Pandas, TensorFlow Spotify (Recommendations)

Web Dev Django, FastAPI Instagram, Pinterest

Automation Selenium, Beautiful Soup NASA, SpaceX

Cloud Computing Boto3, OpenStack Amazon Web Services

Example: Mini Store Receipt Program Sample Output

item = input("Enter item name: ") Enter item name: Notebook


price = float(input("Enter item price: ")) Enter item price: 45.50
quantity = int(input("Enter quantity: ")) Enter quantity: 3

total = price * quantity


----- RECEIPT -----
print("\033[1m"+"\n----- RECEIPT -----" + "\033[0m")
Item: Notebook
print("Item:", item)
Price: 45.5
print("Price:", price)
Quantity: 3
print("Quantity:", quantity)
Total Amount: ₱ 136.5
print("Total Amount: ₱", total)

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.

Bold Start: \033[1m and Reset/End: \033[0m

4
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
GETTING STARTED

1. The "Hello World" Example

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.

Example Sample Output

name = input("What is your name? ") What is your name? Alex


print(f"Hi {name}, welcome to Python!") Hi Alex, welcome to Python!

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

By the end of this section you should be able to

• Display output using the print() function.

• Obtain user input using the input() function.

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.

 Default: A single space (" ").


 Purpose: To change how items are joined together.

Example:
# Default behavior (uses a space)
print("Apple", "Banana", "Cherry")
# Output: Apple Banana Cherry

# Using sep to put a hyphen between them


print("Apple", "Banana", "Cherry", sep="-")
# Output: Apple-Banana-Cherry

# Using sep to put them on new lines


print("Apple", "Banana", "Cherry", sep="\n")
# Output:
# Apple
# Banana
# Cherry

The end Argument


The end parameter defines what character is printed at the very end of the print statement.

 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

# Using end to keep everything on the same line


print("Hello", end=" ")
print("World")
# Output: Hello World

# Using end to add a special closing


print("Processing", end="...")
print("Done!")
# Output: Processing...Done!

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.

Example Daily Store Report Sample Output

print("Daily", "Sales", "Report", sep=" | ") Daily | Sales | Report


print("Date:", "January 9, 2026", sep=" ")
print("Store:", "ABC Mini Mart", sep=" ") Date: January 9, 2026
Store: ABC Mini Mart
print("\nItems Sold:", end=" ")
print("Notebook", "Pen", "Eraser", "Marker", sep=", ") Items Sold: Notebook, Pen, Eraser, Marker
Total Customers: 45
print("Total Customers:", 45) Total Sales: ₱3560.75
print("Total Sales:", "₱", 3560.75, sep="") Status: CLOSED ***
print("Status:", "CLOSED", end=" ***\n")
End of Report
print("\nEnd of Report")

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

1. Write a Python program that displays a simple Daily School


DAILY | SCHOOL | REPORT
Report.
2. You must use the sep parameter in at least two print()
College: College of Technology
statements.
Subject: Python Programming
3. You must use the end parameter in at least two print()
statements.
Teacher: Mr. Reyes
4. The program must produce the exact output shown below.
Students: 40
5. Do not use input().
Status: COMPLETED

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.

Comparison Table: Input Mechanics

Component Role Example

Variable The "Where" (Storage) fav_food

Function The "How" (Action) input(...)

Prompt The "What" (Instruction) "What is your favorite food? "

Example : Student Profile Sample Output

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.

print("\nThank you for registering.") Thank you for registering.

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.

Variable naming rules

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)

1. The Assignment Operator (=)

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."

 Directional Flow: Information always flows from Right to Left.

 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.

 Human-Readable Labels: Variables act as nicknames for these complex addresses.

 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.

3. The Structure of the Statement

An assignment statement must follow a strict structure: Variable = Value.

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

Middle Operator The = sign.

Right Can be a raw value (6), a string ("May 15"), another variable, or a math expression
R-value
Side (6 + 4).

4. Key Differences from Mathematics

To truly master Python, you must understand where math logic and programming logic diverge:

The "Increment" Example

In a math class, the following equation is impossible:

x=x+1

(Because a number cannot be equal to itself plus one).

In Python, this is one of the most common statements:

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

Statement What Python Does Result

age = 25 Stores integer 25 in age. age is 25

name = "Aria" Stores string "Aria" in name. name is "Aria"

new_age = age Looks up age (25) and copies it to new_age. Both are 25

age = age + 1 Calculates 25 + 1 and updates age. age is 26

Rules for naming variables

1. The Strict Syntax Rules

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

o ❌ 1st_place = "Gold" (Invalid)

 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 ❌ user-score = 100 (Python thinks the - is a minus sign)

o ❌ price$ = 5.0 (Invalid)

 No Spaces: Variable names must be a single continuous block of text.

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

o ❌ if = 5, else = 10, print = "Hello", class = "A" (All invalid)

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.

Snake Case (The Standard)

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

A variable name should describe what it holds.

 ❌ a = 3.14 (What is 'a'?)

 ✅ pi_value = 3.14 (Clear and descriptive)

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

3. Summary Table: Good vs. Bad Names

Variable Name Status Why?

player_score ✅ Excellent Follows snake_case and is descriptive.

_temp ✅ Valid Starts with underscore (often used for internal data).

2nd_user ❌ Invalid Starts with a number.

first-name ❌ Invalid Contains a hyphen (minus sign).

True ❌ Invalid It is a Python Keyword (Boolean value).

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

# Constant value Customer Name: Ryan


RATE_PER_KWH = 9.75 Units Used: 120 kWh

# Variables Rate per kWh: ₱ 9.75


customer_name = "Ryan"
Total Bill: ₱ 1170.0
units_used = 120
total_bill = units_used * RATE_PER_KWH

print("Customer Name:", customer_name)


print("Units Used:", units_used, "kWh")
print("Rate per kWh: ₱", RATE_PER_KWH)
print("Total Bill: ₱", total_bill)

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

Objective: To demonstrate understanding of variables, user input, and output statements in


Python.
Sample Output
Instructions
Enter student name: Ryan Agsaluna
1. Ask the user to enter at least five pieces of information
Enter age: 20
about a student (name, age, course, year level, and
Enter course: BSIT
section).
2. Store each piece of information in a separate variable. Enter year level: 1st Year
3. Display all collected information using the print() function. Enter section: A
4. The program’s output must follow the same format as
shown in the Desired Output. STUDENT INFORMATION
--------------------------------------
Name: Ryan Agsaluna
Age: 20
Course: BSIT
Year Level: 1st Year
Code Section
Section: A

18
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
String Basics

Learning objectives

By the end of this section you should be able to

• Use the built-in len() function to get a string's length.

• Concatenate string literals and variables using the + operator.

Quote marks

A string is a sequence of characters enclosed by matching single (') or double (") quotes. Ex: "Happy

birthday!" and '21' are both strings.

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.

1. Quote Marks: The "Container" for Text

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!"'

Simple text Use either. 'Apple' or "Apple"

2. Using len() to Measure Strings

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:

phrase = "Hello World"

print(len(phrase))

# Output: 11 (5 letters + 1 space + 5 letters)

3. String Concatenation (The + Operator)

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

4. Strings vs. Numbers

It is important to distinguish between '21' and 21.

 '21' is a string. Python sees it as the character '2' followed by '1'. You cannot do math with it.

 21 is an integer. Python sees it as a mathematical value.

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').

 ✅ print("It's working") — Success!

Remember!

1. Quotes: Use double quotes if your text has an apostrophe.


2. Length: Use len(my_string) to find out how long it is.
3. Combine: Use + to join two pieces of text, but don't forget to manually add a space " " if you need one!

Example User Profile Sample Output

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)

print("Full Name: " + full_name)


print("Age: " + str(age))
print("Number of characters in name: " + str(name_length))

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.

Example User Profile Generator (Using + for Output) Sample Output

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

full_name = first_name + " " + last_name Full Name: Ryan Agsaluna


name_length = len(full_name) Age: 20
Number of characters in name: 13
print("Full Name: " + full_name)
print("Age: " + str(age))
print("Number of characters in name: " + str(name_length))

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

By the end of this section you should be able to

• Use arithmetic operators to perform calculations.

• Explain the precedence of arithmetic operators.

Numeric data types

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

1. The Integer (int)

An integer is a whole number. It can be positive, negative, or zero, but it can never have a decimal point.

 Examples: 5, -100, 42, 0.


 Use Case: Counting items (e.g., "How many users are logged in?") or representing discrete values (e.g.,
"The year 2026").
 Memory: Python is unique because integers can be as large as your computer's memory allows. There
is no "maximum" limit like in many other languages.

2. The Floating-Point (float)

A floating-point (or "float") represents a real number with a decimal point.

 Examples: 3.14, -0.001, 2.0, 1.5e2 (scientific notation).


 The "Decimal Rule": Even if a number is a whole value, adding a .0 makes it a float. For example, 5 is
an int, but 5.0 is a float.
 Use Case: Measuring things (weight, temperature, distance) or calculating percentages and averages.

3. Data Type Identification

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)

Summary Comparison Table

Data Type Python Name Description Example Remember: Why does "Data Type" matter?

Data types determine what operators you can use. You


Integer int Whole numbers, no decimals. 100 can multiply two floats (2.5 X 4.0), but you cannot
multiply two strings in the same way ("Hello" X "World"
makes no sense to the computer).
Floating-Point float Decimal numbers / fractions. 99.99
Understanding these types prevents "TypeErrors,"
String str Sequence of text/characters. "99.99" which are some of the most common mistakes
beginners make.

Important Warning: The "String" Number

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)

Example Simple Grade Calculator Sample Output

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

print("Quiz Score:", quiz)


print("Exam Score:", exam)
print("Project Score:", project)
print("Total Score:", total)
print("Average Score: {:.2f}".format(average))

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.

1. The Four Basic Operators

Python uses standard symbols for basic math, but remember that the result's data type can change depending
on the operator.

Operator Name Example Result Note

+ Addition 5+2 7 Adds two values.

- Subtraction 5-2 3 Subtracts right from left.

* Multiplication 5*2 10 Uses the asterisk symbol.

/ Division 5/2 2.5 Always returns a float.

Example : Basic Operators Sample Output

# Defining our variables Addition (15 + 4): 19


a = 15 Subtraction (15 - 4): 11
b=4 Multiplication (15 * 4): 60
Division (15 / 4): 3.75
# 1. Addition Precedence (1 + 2 * 3): 7
addition = a + b Precedence ((1 + 2) * 3): 9
print("Addition (15 + 4):", addition)

# 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.

2. Operator Precedence (PEMDAS)

When you have a complex line of math like 10 + 2 * 5,


Python doesn't just go from left to right. It follows the
mathematical order of operations, often remembered by
the acronym PEMDAS.

1. Parentheses ()

2. Exponents (Power of)

3. Multiplication * and Division / (Left to right)

4. Addition + and Subtraction - (Left to right)

Example Walkthrough 1: Standard Precedence

Expression: 1 + 2 * 3

1. Python looks for multiplication first: 2 * 3 = 6.

2. Then it performs addition: 1 + 6 = 7.

Final Result: 7

Example Walkthrough 2: Using Parentheses

Expression: (1 + 2) * 3

1. Parentheses have the highest priority. Python solves 1 + 2 first.

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.

 4 / 2 results in 2.0 (Float)

 10 / 5 results in 2.0 (Float)

This ensures that if there is a remainder (like 5 / 2 = 2.5), the data is not lost.

4. Discussion: Grouping for Clarity

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.

 Hard to read: result = x + y / z * 10

 Easy to read: result = x + ((y / z) * 10)

Both give the same answer, but the second version tells other programmers exactly what your intention was.

Example Precedence Sample Output

# Variables for our math problem Standard Precedence (10 + 5 * 2): 20


x = 10
Using Parentheses ((10 + 5) * 2): 30
y=5 Complex Equation (100 / 10 + 5 * (2 + 1)): 25.0
z=2

# Example 1: Standard PEMDAS (Multiplication before Addition)


# Calculation: 10 + 5 * 2 Explanation
result_standard = x + y * z

# 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

Priority Operator Description

Highest () Parentheses (Anything inside happens first)

Medium *, / Multiplication and Division

Lowest +, - Addition and Subtraction

Example Grocery Store Bill Calculation Sample Output

# Prices of items Total Bill without parentheses: 144.0


bread = 40
milk = 55 Total Bill with parentheses: 190.0
eggs = 12
discount = 10

# Without parentheses (normal precedence)


total1 = bread + milk * 2 - eggs / 2

# With parentheses (controlled calculation)


total2 = (bread + milk) * 2 - eggs / 2

print("Total Bill without parentheses:", total1)


print("Total Bill with parentheses:", total2)

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

bread = float(input("Enter price of bread: ")) Enter price of bread: 40


milk = float(input("Enter price of milk: ")) Enter price of milk: 55
eggs = float(input("Enter price of eggs: ")) Enter price of eggs: 12
discount = float(input("Enter discount amount: "))
Enter discount amount: 10
# Without parentheses (normal precedence)
Total Bill without parentheses: 144.0
total1 = bread + milk * 2 - eggs / 2 - discount
Total Bill with parentheses: 190.0
# With parentheses (controlled calculation)
total2 = (bread + milk) * 2 - eggs / 2 - discount

print("\nTotal Bill without parentheses:", total1)


print("Total Bill with parentheses:", total2)

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.

The Difference between Code and Strings

As your text mentions, context matters. The # only creates a comment if it is "loose" in the code.

 Comment: # This is a note (Python ignores this).


 Code: price = 5 (Python executes this).
 String: tag = "#1 Winner" (Python treats this as literal text because it is inside quotes).

2. Why Use Comments?

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:

A. The "Space" Rule (Readability)

Always put one space after the #.

 ❌ #Calculate total (Harder to read)


 ✅ # Calculate total (Clean and professional)

B. Purpose over Process

Don't use comments to restate what the code clearly says. Instead, describe the intent.

Code Bad Comment (Repeating Code) Good Comment (Explaining Purpose)


x = input() # Get input from user # Retrieve player's secret username
p = 3.14 * r**2 # Multiply 3.14 by r squared # Calculate area of the circle for the UI

4. Code Example: Comments in Action

# Initialize the user's starting score


score = 0
# The game loop follows
print("Welcome to the Quiz!")
ans = input("Is Python fun? ") # Ask for user feedback
# Update score if they say yes
if ans == "yes":
score = score + 10
print("Correct!") # Feedback for the user

Discussion of the Example:


 Header Comment: The first line explains the starting state.
 Inline Comment: ans = input(...) # Ask for user feedback is an inline comment. It sits on the same line
as the code but doesn't interfere with it.
 Logic Explanation: The comment before the if statement explains the "business logic" (why the score is
increasing).

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!")

2. When to Use Docstrings vs. Comments


The primary difference lies in who the message is for and how it is accessed.
Feature Regular Comment (#) Docstring (""")
Placement Anywhere in the code. At the very top of a file or function.
Purpose To explain a specific line or "trick." To provide a manual/summary for the code.
Visibility Hidden from the program's output. Can be read by the program using help().
Length Usually one line. Can be many paragraphs long.

3. The help() Function


The coolest feature of docstrings is that they are "interactive." If you write a docstring at the top of your script,
other programmers can see it by using the help() command.

Example Code: Remember:

""" # This is a comment: It explains a "how" (internal)


CALCULATOR MODULE # It's like a sticky note on a page.
Version: 1.0 """
Author: Gemini This is a docstring: It explains the "what" (external)
This script performs basic math and prints the result to the It's like the 'About the Author' or 'Introduction'
console. section of a book.
"""
print("Running...")
If another programmer wants to know what your script does without reading all your code, they can simply
type help(your_filename). Python will extract the text inside the triple quotes and display it as a manual.

4. Best Practices for Docstrings

1. Be Concise: Start with a one-line summary of what the code does.


2. Use Triple Double Quotes: While ''' works, the standard (PEP 8) recommends """.
3. Detail Inputs/Outputs: If you are documenting a specific task, list what data is needed and what the
result will be.
33
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: School Fund Raising Report

Objective: To demonstrate understanding of integer variables, arithmetic operations, user input,


and the effect of operator precedence in Python.

Instructions: Problem Scenario


Sample Output
A school conducted a fundraising event.
Your task is to create a program that asks the user to enter the
Enter T-Shirt price: 180
following values:
Item Prices Enter Notebook price: 55
 T-Shirt price Enter Ballpen price: 20
 Notebook price Enter number of T-Shirts sold: 5
 Ballpen price Enter number of Notebooks sold: 8
Quantities Sold Enter booth rental cost: 100
 Number of T-Shirts sold Enter event expense: 40
 Number of Notebooks sold
Additional Charges Final Income using normal precedence: 1150.0
 Booth rental Final Income using modified precedence: 2255.0
 Event expense
The program must compute the final income in two different
ways:
1. Using normal operator precedence
2. Using parentheses to modify the order of operations

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.

 Example: In the statement x = 5, the literal 5 is an expression.


 Complex Example: The expression $3x - 5$ evaluates to 7 when $x$ is 4.

The Building Blocks

Expressions are typically constructed using three main components:

1. Literals: Fixed values, such as 3 or 5.


2. Variables: Placeholders for data, such as x.
3. Operators: Symbols that perform calculations, such as * (multiplication) or - (subtraction).

Expressions are highly flexible; they can be as short as a single number or arbitrarily long, spanning multiple
complex calculations.

What’s in This Chapter?

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:

 Experiment with code in real-time using the Python shell.


 Differentiate between integers and floating-point (decimal) numbers.
 Enhance your math capabilities by importing the math module.
 Improve code readability by managing long lines of logic effectively.

Mastering expressions is the key to unlocking more complex and interesting programming calculations.

The Python Shell (Interactive Mode)

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:

1. Read: It reads the command you type.

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.

How to exit: Type exit() or quit().

Example Sample Output

customer = input("Enter customer name: ") Enter customer name: Ryan


year_joined = int(input("Enter year joined: ")) Enter year joined: 2022
Welcome, Ryan
membership_years = 2026 - year_joined Membership Duration: 4 years

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

Total Expenses: 19000.0


Remaining Balance: 6000.0
Code Section

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

1. Implicit Type Conversion (Automatic)

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.

Example Sample Output

# Initial assignment as an integer


distance = 250 Start: 250 (Type: <class 'int'>)
print(f"Start: {distance} (Type: {type(distance)})") Update: 252.5 (Type: <class 'float'>)
Total: 105.5 (Type: <class 'float'>)
# Re-assignment to a decimal value
distance = 252.5
print(f"Update: {distance} (Type: {type(distance)})")

# Mixing types in math


total_miles = 100 + 5.5
print(f"Total: {total_miles} (Type: {type(total_miles)})")

Explanation: Notice that we never told Python to change distance to a


float. The moment we assigned 252.5, the interpreter updated the "box" in memory to hold a float instead of
an integer.

2. Explicit Type Conversion (Manual)

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.

The Three Main Functions:


 int(): Converts to a whole number. Warning: It does not round; it simply cuts off (truncates) the
decimal.
 float(): Converts to a decimal.
 str(): Converts a number into text so it can be combined with other sentences.

38
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Code:

# Scenario: Adding two inputs Output:


num1 = "10" # Strings (e.g., from input())
num2 = "20" Sum: 30
int(5.9) becomes: 5
# Without conversion: "10" + "20" = "1020" Your score is: 100
# With conversion:
sum_result = int(num1) + int(num2)

# Demonstrating truncation with int()


decimal_num = 5.9
converted_int = int(decimal_num)

# Converting number to string for a message


score = 100
message = "Your score is: " + str(score)

print(f"Sum: {sum_result}")
print(f"int(5.9) becomes: {converted_int}")
print(message)

Comparison Summary

Feature Implicit Conversion Explicit Conversion


Who does it? The Python Interpreter. The Programmer.
Why? To prevent data loss in math. To make data compatible for tasks.
Example 5 + 2.0 results in 7.0 int("10") results in 10
Reliability Safe and automatic. Requires care (can't int("Hello")).

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.

Example Sample Output

user_input = "10.75" Output:


# Convert string to float to keep the decimal Original: 10.75 | As Integer: 10
price = float(user_input)
# Convert float to int (losing the decimal)
whole_price = int(price)

print(f"Original: {price} | As Integer: {whole_price}")

Example Sample Output

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

Enter rate per hour: 25.50


salary = hours * rate
Employee: Alex Rivera
print("Employee:", employee)
Total Salary: 1020.0
print("Total Salary:", salary)

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.

Instructions Sample Output

1. Input the customer's name, number of items, and price per


Customer name: Ryan
item.
2. Compute the subtotal, tax, shipping, and total amount due. Number of items: 3
3. Display the complete billing summary Price per item: 1200.50

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.

1. Rule: Integers + Floats = Float

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.

Example Code: Shopping Order

# User enters 3 Output:


quantity = 3 # Data type: int
Result: 15.0
# User enters 5.0 Data Type of total: <class 'float'>
price = 5.0 # Data type: float

# Multiplication of mixed types


total = quantity * price

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.

2. The Division Rule (/)

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.

Example: The Error and the Fix

age = 25 # int
# This will cause a TypeError:
# print("You are " + age + " years old.")

# The Fix: Convert the int to a str


print("You are " + str(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.

1. The Incompatibility Rule

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.

 The Problem: input() always returns a string.


 The Error: Trying to do "10" + 5 results in a TypeError. Python doesn't know if you want to turn the 5
into text (to get "105") or the "10" into a number (to get 15).

2. Explicit Conversion (The Fix)

To combine these types, you must choose your goal:

1. Do you want to do Math? Convert the string to a number.


2. Do you want to display Text? Convert the number to a string.

43
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Code: The "Noor" Scenario

# Noor's mistake Output:


user_input = input("Enter a number: ") # User types 10, stored as "10"
Math Result: 15
# This line would fail: Text Result: 10 plus 5
# result = user_input + 5

# The Correct Way (Math goal)


math_result = int(user_input) + 5

# The Correct Way (Text goal)


text_result = user_input + " plus 5"

print("Math Result:", math_result)


print("Text Result:", text_result)

3. The Repetition Operator (*)

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.

 Rule: String * Integer = The string repeated $N$ times.


 Constraint: You cannot multiply a string by a float (e.g., "Hi" * 2.5 causes an error).

Example Code:

word = "banjo" Output:


print("Standard Repetition:", word * 3)
Standard Repetition: banjobanjobanjo
separator = "-" * 20 --------------------
print(separator) Loading Checkpoint
print("Loading Checkpoint") --------------------
print(separator)

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.")

Example Sample Output

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

Instructions Sample Output

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:

x = 0.1 + 0.1 + 0.1


print(x == 0.3) # This will be FALSE
print(x) # This will be 0.30000000000000004

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.

1. Why Floating-Point Errors Occur

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.

The "Base" Problem

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...

The Round-Off Error

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.

2. Seeing the Error in Action

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

result = 0.1 + 0.2 The result is: 0.30000000000000004


Is result exactly 0.3? False
print("The result is:", result)
print("Is result exactly 0.3?", result == 0.3)

3. The round() Function

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.

Example Sample Output

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

# Fixing the 0.1 + 0.2 error


total = 0.1 + 0.2
print("Fixed total:", round(total, 1))
Fixed total: 0.3
Sample Output
Example

Enter first deposit: 250.75


deposit1 = float(input("Enter first deposit: "))
Enter second deposit: 100.25
deposit2 = float(input("Enter second deposit: "))
Wallet Balance: 351.0
balance = deposit1 + deposit2

print("Wallet Balance:", balance)

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

1. Input four deposit values. Deposit 1: 0.1


2. Compute the total investment. Deposit 2: 0.2
3. Display the result. Deposit 3: 0.3
Deposit 4: 0.4

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)

1. The Three Faces of Division

When you divide two numbers in Python, you have three different operators to choose from depending on
what information you need.

2. Using Floor Division and Modulo Together

A very common pattern in programming is using // and % with the same number (the modulus) to split a large
value into smaller units.

The "Centimeter to Meter" Logic

If you have 193 cm, you know it is 1 meter and 93 centimeters.

 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:

total_cm = 193 Output:

meters = total_cm // 100 # How many full meters? Total: 193cm


remaining_cm = total_cm % 100 # How many cm are left over? Conversion: 1m and 93cm

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:

total_seconds = 135 Output:

minutes = total_seconds // 60 # Modulus is 60 (seconds in a minute) The video length is 2:15


seconds = total_seconds % 60 # Remainder is the extra seconds

print(f"The video length is {minutes}:{seconds}")

4. Key Takeaways and Vocabulary

 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

 Use / if you need a decimal (e.g., calculating an average).


 Use // if you need a whole number (e.g., how many boxes do I need for these items?).
 Use % if you need to know what's left over (e.g., is a number even or odd?).

Example Sample Output

packages = int(input("Enter total packages: ")) Enter total packages: 10


drivers = int(input("Enter number of drivers: ")) Enter number of drivers: 3
Packages per driver: 3.3333333333333335
print("Packages per driver:", packages / drivers)
Whole packages per driver: 3
print("Whole packages per driver:", packages // drivers)

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.

 [Link](x): Square root.


 [Link](x, y): $x$ to the power of $y$.
 [Link](x): Always rounds up to the nearest integer.
 [Link](x): Always rounds down to the nearest integer.

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.

2. Using the import Statement

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().

Example Sample Output

import math The square root of 64 is: 8.0

# Use the sqrt function Note: [Link]() always returns a float,


result = [Link](64) even if the number is a perfect square.
print("The square root of 64 is:", result)

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:

4. Comprehensive Example: Circle Calculator

Let's combine the math module with user input to calculate the area of a circle (Area = pi r^2).

Example Sample Output

import math

# 1. Get user input Enter the radius of the circle: 5


radius_text = input("Enter the radius of the circle: ") A circle with radius 5.0 has an area of 78.54
radius = float(radius_text)

# 2. Perform calculation using math module


# We use [Link] and [Link] (radius squared)
area = [Link] * [Link](radius, 2)

# 3. Output result
print(f"A circle with radius {radius} has an area of {area:.2f}")

Summary

 Import first: Put import math at the top of your script.


 Dot Notation: Always type math. before the function name (e.g., [Link]()).
 Check Types: Most math module functions return a float.
 Constants: [Link] and math.e are variables, not functions, so they don't need parentheses ().

54
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output

import math Enter lot radius: 12

radius = float(input("Enter lot radius: ")) Lot Area: 452.3893421169302


area = [Link] * radius ** 2
Lot Area: 452.39
print("Lot Area:", area)
# Using an f-string with :.2f to format to 2 decimal places
print(f"Lot Area: {area:.2f}")

Explanation

This program introduces Python’s math module for performing accurate mathematical operations. It reflects
real-world usage in engineering and construction calculations.

Graded Activity: Land Survey Computation

Objective: To apply the math module in computing land and pond areas.

Instructions Sample Output

1. Input land dimensions and pond radius. Length of land: 50


2. Compute individual areas and total land area. Width of land: 30
3. Display formatted results. Radius of pond: 7

Land Area: 1500.0


Pond Area: 153.94
Code Section
Total Area: 1653.94

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

Guidelines for Spaces

To ensure consistency and readability, the Python community follows specific spacing guidelines.

Guideline Example Common Mistakes

Parentheses: No space before or after


print("Go team!") print ("Go team!") or print( "Go team!" )
the bracket.

Commas: No space before, but one print("Hello" , name) or


print("Hello", name)
space after. print("Hello",name)

Assignment: One space before and name = input("Your name? name=input("Your name?") or name
after the = sign. ") =input("Your name? ")

Concatenation: One space before and


print("Hi", name + "!") print("Hi", name+"!")
after the + sign.

Arithmetic: Use spaces to visually


x**2 + 5*x - 8 x ** 2 + 5 * x - 8
show lower precedence.

Strategic Spacing in Arithmetic

A sophisticated way to use spacing is to group high-precedence operations closer together.

 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.

Why Good Spacing Matters

 Clarity: Compressed code like name=input can be confusing to scan quickly.


 Collaboration: Other programmers are more likely to understand and work with code that follows
standard community guidelines.
 Consistency: Adhering to these rules (often found in a document called PEP 8) makes your code look
professional.

Example Comparison

 Good Spacing: print(name, "should visit", place + "!")


 Poor Spacing: print( name,"should visit" , place+ "!")

Example Sample Output

# Following the guidelines for assignment and parentheses


user_name = input("Enter your name: ")
score = 10 Enter your name: Alex
Congratulations Alex!
# Following guidelines for arithmetic and concatenation Your final score is: 25
# Note the lack of spaces around * to show it happens first
final_score = score*2 + 5
print("Congratulations", user_name + "!")
print("Your final score is:", final_score)

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.

1. The 80-Character Rule (PEP 8)

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.

Core Principles of PEP 8

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

 Rule: Use 4 spaces per indentation level.


 Why: It creates a clear visual hierarchy so you can easily see which blocks of code belong together.

2. Naming Conventions

PEP 8 suggests specific "cases" for different types of names:

 Variables & Functions: Use snake_case (all lowercase with underscores).


o Example: calculate_total_price()
 Classes: Use PascalCase (capitalize every word).
o Example: UserProfile
 Constants: Use UPPERCASE_SNAKE_CASE.
o Example: MAX_RETRY_LIMIT = 5

3. Maximum Line Length

 Rule: Limit all lines to a maximum of 79 characters.


 Why: This allows programmers to open two files side-by-side on a screen without having to scroll
horizontally.

4. Whitespace

 Surround operators with a single space: x = y + 1 (Correct) vs x=y+1 (Incorrect).


 Avoid extra spaces inside parentheses: print(x) (Correct) vs print( x ) (Incorrect).

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.

Example Sample Output

# 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.

A. Explicit Line Joining (\)

You can use a backslash (\) at the end of a line to tell Python that the statement continues on the next line.

 Note: PEP 8 recommends avoiding this method whenever possible.

B. Implicit Line Joining (Parentheses)

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.

Example Sample Output

# 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."

# Implicit Line Joining (Best practice)


line_2 = ("This uses parentheses to "
"join lines naturally.")

print(line_1)
print(line_2)

59
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output

price = float(input("Enter item price: ")) Enter item price: 149.50


qty = int(input("Enter quantity: "))
Enter quantity: 3
total = price * qty Total Amount: ₱448.50

print("Total Amount: ₱{:.2f}".format(total))

Explanation

The program demonstrates formatted output to display monetary values correctly. Proper formatting is
essential in business and financial applications.

Graded Activity: Hotel Billing Statement

Objective: To generate a professional billing statement using formatted output

Instructions Sample Output

1. Input guest information and room details. Guest name: Mark


2. Compute charges and service fees. Number of nights: 3
3. Display a formatted billing statement.
Rate per night: 2450.75

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!

# Using an f-string to combine text and variables


# The items in curly braces { } are replacement fields
message = f"Good morning, {first} {last}! Your score is {score}."

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

# Variables following standard assignment spacing


population = 12345678
growth_rate = 5 Current Population: 12,345,678

# Using f-strings with format specifiers and correct comma spacing Growth Rate: 5 Next Year: 12,962,961
print(f"Current Population: {population:,d}")

# Using f-strings for alignment (15 characters wide)


print(f"Growth Rate: {growth_rate:15d}")

# Strategic spacing in arithmetic: spaces around + but not *


# This visually shows that multiplication happens first
next_year_estimate = population + population*0.05

print(f"Next Year: {int(next_year_estimate):,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.

2. Ways to Create an Empty List


There are two standard ways to define an empty list in Python:
1. Square Brackets: list_1 = []
2. The list() Constructor: list_1 = list()

3. Example Code: Creating and Using Lists

# 1. Defining an empty list Output


shopping_cart = [] Plaintext
Empty List: []
# 2. Defining a list with various data types Mixed List: [2, 'Hello', 2.5]
# This list contains an integer, a string, and a float Numbers: [10, 20, 30, 40]
my_data = [2, "Hello", 2.5] The type of 'numbers' is: <class 'list'>

# 3. Defining a simple integer list


numbers = [10, 20, 30, 40]

# Displaying the lists and their types


print(f"Empty List: {shopping_cart}")
print(f"Mixed List: {my_data}")
print(f"Numbers: {numbers}")
print(f"The type of 'numbers' is: {type(numbers)}")

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.

2. Accessing Elements (Indexing)


Each element in a tuple is assigned a specific position called an index.
 The index always starts at 0 for the first element.
 You access an element by placing the index number in square brackets [] next to the tuple name.

3. The Concept of Immutability


A key feature of a tuple is that it is immutable. This means that once a tuple is created, its elements cannot be
changed, added, or removed.
 Benefit: Tuples are faster than lists and protect data from being accidentally modified.
 Comparison: Use a list if you need to change data later; use a tuple if the data should remain constant
(like the coordinates of a city or the RGB values of a color).

4. Example Code: Creating and Accessing a Tuple

# 1. Creating a tuple with mixed types Output


# Conventionally surrounded by parentheses
user_data = ("Alice", 25, 5.7) Name: Alice
Age: 25
# 2. Accessing elements by index
Height: 5.7
name = user_data[0] # First element
Object type: <class 'tuple'>
age = user_data[1] # Second element
height = user_data[2] # Third element

# 3. Displaying the data


print(f"Name: {name}") # Note: Trying to change an element
print(f"Age: {age}") would cause an error:
print(f"Height: {height}") # user_data[1] = 26 --> This would
result in a TypeError
# 4. Demonstrating the type
print(f"Object type: {type(user_data)}")

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

item1 = input("Enter item 1: ") Enter item 1: Smartphone


item2 = input("Enter item 2: ") Enter item 2: T-shirt
item3 = input("Enter item 3: ") Enter item 3: Apples
Inventory: ['Smartphone', 'T-shirt', 'Apples']
inventory = [item1, item2, item3] Departments: ('Electronics', 'Clothing', 'Groceries')
departments = ("Electronics", "Clothing", "Groceries")

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.

Graded Activity: Company Asset Registry

Objective: To generate a professional billing statement using formatted output

Instructions Sample Output

1. Input four company assets. Asset 1: Laptop


2. Store them in a list and display them. Asset 2: Printer
3. Display predefined office locations using a tuple. Asset 3: Router
Asset 4: Projector

Assets: ['Laptop', 'Printer', 'Router', 'Projector']


Code Section Office Locations: ('Manila', 'Cebu', 'Davao', 'Iloilo')
Number of Assets: 4

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.

3.1 Boolean Values

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.

1. Key Features of Booleans

 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.

2. Examples and Usage

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.

Example Sample Output

# Direct assignment Likes Pineapple: True


likes_pineapple = True Is Adult: True
is_tuesday = False Type: <class 'bool'>

# Booleans resulting from a comparison


age = 20
is_adult = age >= 18

print(f"Likes Pineapple: {likes_pineapple}")


print(f"Is Adult: {is_adult}")
print(f"Data Type: {type(likes_pineapple)}")
68
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Explanation

 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'>.

Comparison with Strings

It is a common mistake to put quotes around a Boolean. Note the difference:

 status = True  A Boolean (Used for logic).


 status = "True"  A String (Just a piece of text; cannot be used directly for logic).

Example Sample Output

is_raining = True Is it raining? True


is_sunny = False Type: <class 'bool'>

print(f"Is it raining? {is_raining}")


print(f"Type: {type(is_raining)}")

Example Sample Output

# Demonstrating Python Booleans Is Python fun? True

is_python_fun = True Is coding hard? False


is_coding_hard = False The data type of 'True' is: <class 'bool'>

print(f"Is Python fun? {is_python_fun}")


print(f"Is coding hard? {is_coding_hard}")

# Checking types
print(f"The data type of 'True' is: {type(is_python_fun)}")

# Example of case sensitivity (This would cause an error if


uncommented)
# my_bool = true # NameError: name 'true' is not defined

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.

Example Sample Output

# Comparison Operators in Action Score: 85

my_score = 85 Is the score passing? True


passing_score = 70
Is it a perfect score? False

# Greater than Is the score non-zero? True


is_passing = my_score > passing_score

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

An if statement consists of two primary parts:

 The Condition: An expression that evaluates to either True or False.


 The Body: A group of statements that execute only if the condition is True.

Formatting and Indentation

In Python, the formatting of the statement is critical for it to function correctly:


 Indentation: The body of the statement must be grouped together using exactly one level of
indentation.
 PEP 8 Standards: The official style guide recommends using four spaces per indentation level.
 No Empty Bodies: The Python interpreter will produce an error if the body of an if statement is left
empty.
Sample Output
Example

is_rainy = True

# An if statement's body must be grouped together and have one level of


indentation.
Grab an umbrella!
if is_rainy: Have a nice day.
# PEP 8 recommends four spaces per indentation level.
print("Grab an umbrella!")

print("Have a nice day.")

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

# If the condition (total < 0) is true, the body is executed.


if total < 0:
print("Error: The total is a negative number.")

Explanation

 Calculation: 10 + (-50) results in -40.


 The Condition: Python checks if -40 < 0. Since this is True, the body executes.
 Formatting: Notice the colon (:) at the end of the if line and the four-space indentation for the print
statement.

3. If Statement with a String Condition

You can also use if statements to check text input.


Sample Output
Example

password_attempt = "12345"

if password_attempt == "12345": Access Granted.


print("Access Granted.") Welcome back, User.
print("Welcome back, User.")

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

1. How the If-Else Statement Works

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!")

The structure evaluates a condition to determine which branch of code to


follow:

 The If Branch: Executed only if the condition is True.


 The Else Branch: Executed only if the condition is False.

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.

2. Example: Grading System

In this scenario, a program checks if a student passed a test based on a minimum score.

Example Sample Output

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

 Evaluation: The interpreter evaluates 65 >= 70, which results in False.


 Branching: Because the condition is False, the code inside the if block is entirely skipped.
 Result: The program jumps directly to the else block and executes the instructions found there.

3. Example: Even or Odd Checker

This example uses the modulo operator (%) to decide if a number is even or odd.

Example Sample Output

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.

Example Sample Output

# Example: Adding two numbers and checking for a negative result


num1 = -15
num2 = 5 Error: The result is negative.
total = num1 + num2

# The condition: is the total less than 0?


if total < 0:
# This is the body: indented by 4 spaces
print("Error: The result is negative.")
else:
# This executes only if the condition is False
print(f"The result is valid: {total}")

74
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Explanation

 Evaluation: The program first calculates the total ($-10$).


 Condition Check: The interpreter evaluates total < 0. Since $-10$ is less than $0$, the condition is True.
 Execution: Because the condition is True, the program enters the first indented block and prints the
error message.
 Skipping: The else block is completely ignored because the if condition was met.

Code Review

Code Sample Output Explanation


age = int(input("Enter your age: ")) Enter your age: 20
Access granted.
if age >= 18:
print("Access granted.")
else:
print("Access denied.")
balance = float(input("Enter account balance: ")) Enter account balance: 5000
withdraw = float(input("Enter withdrawal amount: ")) Enter withdrawal amount: 3000
Transaction approved.
if withdraw <= balance:
print("Transaction approved.")
else:
print("Insufficient funds.")

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.

The Truth Tables

A truth table shows the result of every possible combination.

Operator Rule Example Result


and True only if both parts are true. (5 > 3) and (2 > 1) True
or True if at least one part is true. (5 > 3) or (1 > 2) True
not Flips the value (Inverter). not (5 > 3) False

2. Comprehensive Discussion & Examples

A. The and Operator

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

age = 70 Output: True


has_card = True
print(age > 65 and has_card)

 Explanation: Since both conditions are True, the


entire expression evaluates to True.

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.

 Example: Checking if it is the weekend (either Saturday OR Sunday).

day = "Saturday" Output: True


print(day == "Saturday" or day == "Sunday")

 Explanation: Only one side needs to be correct for the


whole thing to pass.

C. The not Operator

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."

3. Interpreting if-else with Logic

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

if balance >= withdrawal_amount and account_active:


print("Withdrawal successful.")
else:
print("Transaction denied.")

 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).

Example Sample Output

has_key = True
door_unlocked = False
You can enter the room.
if has_key or door_unlocked:
print("You can enter the room.")

Graded Activity: Student Scholarship Eligibility

Objective: To apply Boolean logic, comparisons, and decision statements in determining eligibility

Instructions Sample Output

1. Ask the user for GPA and family income.


2. If GPA is 3.5 or higher and income is ≤ 20000, print "Eligible Enter GPA: 3.7
for Scholarship".
Enter family income: 18000
3. Otherwise, print "Not Eligible".
Eligible for Scholarship

Code Section

78
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
3.4 Operator Precedence

When an expression has multiple operators, which


operator is evaluated first? Precedence rules provide
the priority level of operators. Operators with the
highest precedence execute first. Ex: 1 + 2 * 3 is 7
because multiplication takes precedence over addition.
However, (1 + 2) * 3 is 9 because parentheses take
precedence over multiplication. Just like math has
PEMDAS, Boolean logic has an order of operations.

1. Arithmetic operators (+, -, etc.) happen first.


2. Relational operators (>, <, ==) happen second.
3. Boolean operators happen last, in the order of not, then and, then or.

Example Sample Output


:
# result = 10 + 2 > 15 or not 5 == 5
# 1. Arithmetic: 10 + 2 -> 12
# 2. Relational: 12 > 15 -> False; 5 == 5 -> True Is winner? False
# 3. Not: not True -> False
# 4. Or: False or False -> False

score = 10
bonus = 2
is_winner = score + bonus > 15 or not score == 0

print(f"Is winner? {is_winner}")

3.5 Chained Decisions (if-elif-else)

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.

Why use elif instead of multiple if statements?

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.

The Error: Using Multiple if Statements

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:

# First check Final Score: 75


if score < 70:
score += 10 # Score becomes 70

# Second check (Evaluated independently)


if 70 <= score < 85:
score += 5 # Score becomes 75

print(f"Final Score: {score}")

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.

The Fix: Using elif for Chained Decisions

By chaining the statements, Python stops checking as soon as it finds a match.


Sample Output
Example

score = 60 Output:

if score < 70: Corrected Score: 70


score += 10 # This runs, and Python skips the rest of the chain
elif 70 <= score < 85:
score += 5 # This is ignored because the first condition was True

print(f"Corrected Score: {score}")

Real-World Example: Travel Layover Alert

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:

if layover_hours > 24: Alert: Possible missed


print("Suggestion: Book a hotel room.") connection!
elif layover_hours < 1:
print("Alert: Possible missed connection!")
else:
print("Layover time is standard.")

80
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output

temp = 25

if temp > 30:


It's warm.
print("It's hot.")
elif temp > 20:
print("It's warm.")
else:
print("It's cold.")

Graded Activity: Smart Door Lock System

Objective: To apply logical operators and operator precedence in access control.

Instructions Sample Output

1. Ask for passcode and fingerprint status.


2. Unlock if passcode is correct AND fingerprint is verified OR Enter passcode: 4321
emergency override is True.
Fingerprint verified (yes/no): yes
Emergency override (yes/no): no
Door unlocked.

Code Section

81
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output

severity = int(input("Severity level (1-10): "))

status = "High Priority" if severity >= 7 else "Normal Priority"


Severity level (1-10): 8
Patient status: High Priority
print("Patient status:", status)

Graded Activity: Smart Door Lock System

Objective: To apply nested decision structures and conditional expressions in a real-world


context.
Sample Output
Instructions

1. Ask for years of service and performance rating.


2. If years ≥ 5: Years of service: 6
 If rating ≥ 90 → "Promotion Approved"
Performance rating: 92
 Else → "Performance Review Required"
3. Otherwise → "Not Eligible for Promotion" Promotion Approved

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.

The Flow of Logic

1. The Outer if is checked first.


2. If the outer condition is False, the entire inner block is skipped.
3. If the outer condition is True, the program moves inside and evaluates the Inner if.

2. Implementing Nested Decisions

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.

Code Example: Movie Ticket Pricing

Example Sample Output

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

 Step 1: The program checks age < 18. This is True.


 Step 2: It enters the "inner" world. It checks has_student_id. This is True.
 Step 3: It prints the student discount. It ignores the else (Minor Rate) and the far-outer else (Standard
Rate).

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

Redundant Code Improve version

if game == 1 and players < 2: if game == 1:


print("Not enough players") if players < 2:
if game == 1 and players > 4: print("Not enough players")
print("Too many players") elif players > 4:
if game == 1 and (2 <= players <= 4): print("Too many players")
print("Ready to start") else:
if game == 2 and players < 3: print("Ready to start")
print("Not enough players") if game == 2:
if game == 2 and players > 6: if players < 3:
print("Too many players") print("Not enough players")
if game == 2 and (3 <= players <= 6): elif players > 6:
print("Ready to start") print("Too many players")
else:
print("Ready to start")

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

Example: Nested if-else (The "Branching" Path)

Imagine a "Game Over" screen logic:

Example Sample Output

game_over = True Output:


high_score = 1000
current_score = 1200 Plaintext
Game Over!
if game_over: New High Score!
print("Game Over!")
if current_score > high_score:
print("New High Score!")
else:
print("Try again to beat the record.")
else:
print("Keep playing!")

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.")

3.7 Conditional Expressions

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

The structure of a conditional expression feels a bit like an English sentence:

2. Examples and Explanation

Example A: Simple Pass/Fail

Imagine you are grading a test. If the score is 60 or higher, they pass; otherwise, they fail.

Traditional if-else: Using a Conditional Expression:

score = 75 score = 75
if score >= 60: result = "Pass" if score >= 60 else "Fail"
result = "Pass" print(result)
else:
result = "Fail"

Output: Pass Output: Pass

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

order_total = 120 Output: Your discount is $20


discount = 20 if order_total > 100 else 0
print(f"Your discount is ${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

Objective: To apply conditional statements and nested decision-making in evaluating a student’s


eligibility for university enrollment and scholarship recommendation.

Instructions Sample Output

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.

4.1 The while Loop

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

Example Sample Output

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

count = 1 Output: The loop checks if count is < 3.


while count <= 3: Hello!
print("Hello!") It prints Hello" and adds 1 to
Hello!
count += 1 the count. Once the count
Hello!
reaches 4, the condition
becomes False, and the loop
stops.
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!")

Example Sample Output Explanation

attempts = 0 Enter PIN The loop allows only 3


attempts. Once the condition
while attempts < 3: Enter PIN
becomes false, the loop stops.
Enter PIN
print("Enter PIN")
Card Blocked
attempts += 1

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

Item: $10 -> With Tax: $11.00


prices = [10, 20, 30]
Item: $20 -> With Tax: $22.00
total = 0
Item: $30 -> With Tax: $33.00
Grand Total: $66.00
for price in prices:
taxed_price = price * 1.10
total += taxed_price
print(f"Item: ${price} -> With Tax: ${taxed_price:.2f}")

print(f"Grand Total: ${total:.2f}")

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.

Range () function in for loop

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

Code Output Explanation


Counting Up (Standard) Counting: 0 Python starts at 0 by default and
This is the most common use case. If you want to print a Counting: 1 stops just before reaching 3.
message 5 times, you use range( 5). Counting: 2

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

Key Concepts to Remember

 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

Code Output Explanation


for row in range(2): Row 0, Col 0 Think of this like a clock: the
for col in range(2): Row 0, Col 1 minute hand (inner loop) must go
print(f"Row {row}, Col {col}") Row 1, Col 0 all the way around before the
Row 1, Col 1 hour hand (outer loop) moves one
tick.

for day in ["Monday", "Tuesday"]: --- Monday --- The Components


 The Outer Loop: for day in
print(f"--- {day} ---") Morning: Exercise ["Monday", "Tuesday"]: This loop
Morning: Breakfast manages the "Big Picture." It will
# Inner Loop 1: Morning tasks Evening: Study run exactly two times (once for
Monday and once for Tuesday).
for task in ["Exercise", "Breakfast"]: Evening: Sleep  The Inner Loops: These are the two
print(f" Morning: {task}") --- Tuesday --- . separate for task loops indented
under the first one. They represent
Morning: Exercise
the "Sub-tasks" that happen inside
# Inner Loop 2: Evening tasks Morning: Breakfast every single day.
for task in ["Study", "Sleep"]: Evening: Study
2. Step-by-Step Execution Path
print(f" Evening: {task}") Evening: Sleep  The computer follows a very strict
"top-to-bottom" order for each
iteration of the outer loop:

 First Big Cycle (Monday):


 Outer Loop starts: day is set to
"Monday".
 Print Header: It prints --- Monday --
-.
 Inner Loop 1 Runs: It iterates
through the morning tasks. It must
print both "Exercise" and
"Breakfast" before it can move
down.
 Inner Loop 2 Runs: It iterates
through the evening tasks. It prints
both "Study" and "Sleep".
 Cycle Ends: Only now is the
Monday iteration complete.
 Second Big Cycle (Tuesday):
 Outer Loop moves on: day is set to
"Tuesday".
 Repeat everything: It prints the
Tuesday header and runs both
inner loops all over again from the
start.

96
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Student Score Analyzer

Objective: To demonstrate correct usage for loop.

Instructions Sample Output

A teacher recorded the quiz scores of 10 students. Enter score of student 1: 80


Write a program that: Enter score of student 2: 90
Enter score of student 3: 60
1. Asks the user to input 10 quiz scores.
Enter score of student 4: 75
2. Stores each score.
Enter score of student 5: 85
3. Computes:
o The total score Enter score of student 6: 70
o The average score Enter score of student 7: 88
o The number of students who passed (score ≥ 75) Enter score of student 8: 92
4. Displays the results. Enter score of student 9: 78
Enter score of student 10: 65
Note
 Use a for loop with range(). Total Score: 783
 Use variables to accumulate total and count passing Average Score: 78.3
students. Number of students passed: 7
 Display all results at the end.

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.

 break: Immediately exits the loop entirely.


o Example: Stop searching once you find the item you're looking for.
 continue: Skips the rest of the current turn and jumps straight to the next iteration.
o Example: Skip printing "Even" numbers in a list of integers.

The break Statement

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.")

2. The continue Statement

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

for i in range(1, 6): Number 1 is Odd.


if i % 2 == 0: Number 3 is Odd.
continue # Skip the print line below and go to the next 'i' Number 5 is Odd.
print(f"Number {i} is Odd.")

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.

1. How Loop Else Works

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."

2. Comprehensive Discussion & Examples

A. Implementing with a for Loop (Searching)

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

fruits = ["apple", "banana", "cherry"] Item not in the list.


search_for = "orange"

for fruit in fruits:


if fruit == search_for:
print("Found it!")
break
else:
# This runs because "orange" was never found (no break occurred)
print("Item not in the list.")

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.

Example Sample Output

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!")

3. Why use Loop Else?

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."

Traditional Method (Using a Flag) Pythonic Method (Using Loop Else)


found = False for item in items:
for item in items: if item == target: break
if item == target: found = True; break else:
if not found: print("Not found") print("Not found")

4. Key Takeaways

 The Interruption: If a break is executed, the else block is ignored.


 The Completion: If the loop finishes because the range ended or the while condition became false, the
else block executes.
 Continue: A continue statement does not stop the else block from running; only break does.

100
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity: Secure Access Scanner

Objective: Students will demonstrate mastery of:


Sample Output
 Controlled iteration using for loops
 Loop interruption with break
 Skipping logic using continue Enter target employee ID: 102
 Conditional completion using for–else Enter employee ID #1: 88
Enter employee ID #2: -5
Scenario
Invalid ID. Skipped.
Enter employee ID #3: 91
A security system checks a list of employee ID numbers.
Write a program that: Enter employee ID #4: 102
Access granted. Welcome!
1. Accepts 5 employee IDs from the user.
2. Skips invalid IDs (negative numbers) using continue.
3. Searches for a target ID. Enter target employee ID: 300
4. Stops the search immediately if the ID is found using break. Enter employee ID #1: 110
5. If the loop finishes without finding the target ID, display Enter employee ID #2: 140
"Access denied. ID not found." using for–else. Enter employee ID #3: 155
Enter employee ID #4: 160
Instructions Enter employee ID #5: 170
Access denied. ID not found.
1. Use a for loop to accept exactly 5 inputs.
2. Use continue for invalid IDs.
3. Use break when the target ID is found.
4. Use the else clause attached to the for loop.

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.

5.1 Defining Functions & Benefits of a Function

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.

Basic Format How It Works

def function_name(parameters):  def defines a function.


# body of the function  The function name identifies the task.
return value  Parameters receive input values.
 The body contains the operations.
 return sends back a result.

Example Sample Output and Explanation

Student Grade Calculator

def compute_average(score1, score2, score3):


Average: 87.67
average = (score1 + score2 + score3) / 3
return average The function calculates and returns the student's
average grade.
avg = compute_average(85, 90, 88)
print("Average:", avg)

102
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output and Explanation

ATM Balance Check Your current balance is: 1250

def check_balance(balance): The function displays the user's current account


print("Your current balance is:", balance) balance.

check_balance(1250)

Example Sample Output and Explanation

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

Example Sample Output and Explanation

# 1. Defining the Function


def apply_discount(customer_name, membership_type, Enter Customer Name: Sarah Jones
original_price): Enter Membership Type (Standard/Premium): Premium
if membership_type.lower() == "premium":
Enter Item Price: 200
discounted_price = original_price * 0.90 # 10% off
Welcome back, Sarah Jones! Premium discount applied.
print(f"Welcome back, {customer_name}! Premium
Final Amount to Pay: $180.00
discount applied.")
return discounted_price
else:
A function is defined using the def keyword and a unique
print(f"Welcome, {customer_name}!") name to hold a specific set of instructions and parameters
return original_price for later use. The indented "body" of the function contains
the logic that processes information, while the return
# 2. Getting User Input statement sends the final output back to the main program.
name = input("Enter Customer Name: ") To execute this logic, you "call" the function by passing real
membership = input("Enter Membership Type data as arguments, allowing the program to reuse the same
(Standard/Premium): ") math for different customers.
price = float(input("Enter Item Price: "))

# 3. Calling the Function


final_price = apply_discount(name, membership, price)

# 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

Objective: To design a Python program that captures customer information, applies


functional programming principles, integrates decision-making using conditional
statements, and generates a properly formatted billing summary.

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.

Basic Format How It Works

if condition:  The condition is evaluated.


statements  If true, the first block runs.
else:  Otherwise, the else block runs.
statements

Example Sample Output and Explanation

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

Example Sample Output and Explanation

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)

Example Sample Output and Explanation

Number is positive, negative, or zero.

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.

Example Sample Output and Explanation

x = 100 Inside: 100 20


Outside: 100
def show():
y = 20
print("Inside:", x, y) y is only inside the function; x is global.

show()
print("Outside:", x)

Example Sample Output and Explanation

# This is a global variable Welcome Alice to Tech Gadgets Inc.!


store_name = "Tech Gadgets Inc." Thank you for visiting Tech Gadgets Inc.

def display_welcome(customer): Global variables are defined outside functions, allowing


# The function can 'see' the global variable them to be accessed and shared across the entire
print(f"Welcome {customer} to {store_name}!") program for consistent data like configuration settings.
However, they should be used sparingly because they
display_welcome("Alice") can make debugging difficult if multiple parts of the
print(f"Thank you for visiting {store_name}.") code attempt to modify them simultaneously.

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.

Basic Format of Arguments How It Works

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)

Example Sample Output and Explanation

Payroll System Weekly Salary: 6000

def calculate_salary(rate, hours):


return rate * hours The function calculates salary using the given pay rate and
number of work hours. The parameters are rate and hours,
salary = calculate_salary(150, 40) and the arguments during the function call are 150 and 40.
print("Weekly Salary:", salary)

110
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Examples Sample Output and Explanation

Shipping Fee Shipping Cost: 400.


The shipping_fee function defines two parameters, weight
def shipping_fee(weight, price_per_kg): and price_per_kg, to create a reusable formula for
return weight * price_per_kg calculating transportation costs. When the function is called
with the arguments 5 and 80, it multiplies them together and
print("Shipping Cost:", shipping_fee(5, 80)) returns the value 400 to be printed as the final shipping cost.

Exam Score Percentage Percentage: 90.0

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.

Online Order Laptop Total: 90000


The order function is defined with three parameters—item, quantity, and
def order(item, quantity, price):
price—which it uses to calculate and display the total cost of a specific
total = quantity * price
purchase. This code uses keyword arguments during the function call,
print(item, "Total:", total)
allowing the data to be passed in any order because the values are
order(item="Laptop", price=45000, explicitly assigned to their corresponding parameter names.
quantity=2)

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.

Basic Format How It Works


def function_name():
return value  The return statement ends the function.
 The value after return is sent back to the caller.
 The returned value can be stored or used in expressions.

Example Sample Output and Explanation

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)

Example Sample Output and Explanation

Fuel Consumption Fuel Cost: 720

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.

Example Sample Output and Explanation

Final Grade: 87.67


Final Grade
The final_grade function is defined with three parameters
def final_grade(prelim, midterm, final): representing different exam scores, which it uses to calculate and
return (prelim + midterm + final) / 3 return the average of the three inputs. When the function is
called with the arguments 85, 90, and 88, it processes the sum
print("Final Grade:", final_grade(85, 90, 88)) and division, allowing the final result to be printed directly as the
customer's average grade.

113
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output and Explanation

# GLOBAL SCOPE: Accessible by all functions


TAX_RATE = 0.10 --- Employee Information Input ---
Enter Employee Name: Alex Rivera
def calculate_net_pay(employee_name, hours_worked, Enter Residential Address: 742 Evergreen Terrace
hourly_rate): Enter Total Hours Worked: 45
# LOCAL SCOPE: These variables exist only inside this Enter Hourly Rate ($): 20.00
function Note: A $100.00 bonus was added to Alex
gross_pay = hours_worked * hourly_rate Rivera's salary for overtime.

# Logic: Bonus for hard work ========================================


if hours_worked > 40: OFFICIAL PAYSLIP
bonus = 100.00 ========================================
gross_pay += bonus EMPLOYEE: ALEX RIVERA
print(f"Note: A $100.00 bonus was added to ADDRESS: 742 Evergreen Terrace
{employee_name}'s salary for overtime.") TAX RATE: 10.0%
---------------------------------------------
# Applying the global tax rate NET PAYABLE AMOUNT: $900.00
tax_deduction = gross_pay * TAX_RATE ========================================
net_pay = gross_pay - tax_deduction
1. Scope: The TAX_RATE is placed in the global
return net_pay scope so it can be updated in one place for
the entire company, while gross_pay is in the
# 1. Collecting User Input local scope to keep individual employee
print("--- Employee Information Input ---") calculations private and separate.
emp_name = input("Enter Employee Name: ") 2. Passing Data: When
emp_address = input("Enter Residential Address: ") calculate_net_pay(emp_name, hrs, pay_rate)
hrs = float(input("Enter Total Hours Worked: ")) is called, the program copies the data from
pay_rate = float(input("Enter Hourly Rate ($): ")) your inputs (arguments) into the function's
placeholders (parameters) to run the math.
# 2. Calling the function with Arguments 3. Returning Results: The return statement acts
# (emp_name, hrs, pay_rate) are the arguments passed to as the bridge that sends the finished
the parameters calculation back out of the function so it can
final_salary = calculate_net_pay(emp_name, hrs, pay_rate) be formatted and printed in the final payslip.

# 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.

6.1 Module Basics

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

Main Program Important Rule:


import math_utils If you create your own module (for example [Link]), the
file that imports it ([Link]) must be in the same folder.
print(math_utils.add(3, 4))

Example Payroll Calculations Sample Output and Explanation

[Link] Salary: 6000


def compute_salary(rate, hours):
return rate * hours Explanation:
The payroll logic is separated into its own
[Link] module for reuse in other company systems.

import payroll

salary = payroll.compute_salary(150, 40)


print("Salary:", salary)

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

print("Average:", [Link]([85, 90, 88]))

Example Professional Land Area Module Sample Output and Explanation

# [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.

Basic Structures How It Works


import module_name
from module_name import function_name  import module imports the entire module.
from module_name import *  from module import name imports specific
parts.
 * imports everything from the module.
Examples
Sample Output and Explanation

Importing Functions Only 4.0


from math import sqrt Only the sqrt function is imported.
print(sqrt(16))
Multiple Imports 8.0
from math import pow, pi 3.141592653589793
print(pow(2, 3))
print(pi)
import math --- Architectural Design Tool ---
Enter Project Name: Construction of Rotunda
def calculate_circle_details(radius): Enter Floor Radius (meters): 50
# Using [Link] for maximum precision
===========================================
# Using [Link](radius, 2) is another way to do radius ** 2
area = [Link] * [Link](radius, 2) DESIGN SPECS: CONSTRUCTION OF ROTUNDA
circumference = 2 * [Link] * radius ===========================================
return area, circumference RADIUS: 50.0 m
FLOOR AREA: 7853.98 sq. meters
# 1. Collecting Project Data PERIMETER: 314.16 meters
print("--- Architectural Design Tool ---") ---------------------------------------------
project_name = input("Enter Project Name: ") MATH CONSTANT USED (PI): 3.141592653589793
r_value = float(input("Enter Floor Radius (meters): "))

# 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.

Basic Structure How It Works


pip install package_name
import package_name 1. pip downloads the module from PyPI.
2. The module is installed into Python’s environment.
3. It becomes available for import in any program.

Examples Sample Output and Explanation

Web Requests 200

pip install requests The requests module simplifies web communication.


import requests The command pip install requests is used in the terminal to
download and install the third-party Requests library, which is a
response = powerful tool for allowing Python to communicate with the
[Link]("[Link] internet. The code itself sends a "get" request to a web server and
print(response.status_code) retrieves a status code, such as 200, to confirm if the connection
was successful and the website is reachable.
Data Analysis 20.0

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)

pip install pyautogui This module enables GUI automation.


import pyautogui The command pip install pyautogui installs a third-party automation
library that allows Python to control the mouse and keyboard to
print([Link]()) interact with other applications. In the code, the [Link]()
function retrieves the primary monitor's resolution, returning the
screen's width and height in pixels as a "Size" object.

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. ----------------------------------

Note: Perform this in command prompt

 To install in your Python Environment: C:\Path\To\Your\[Link] -m pip install pyjokes


 To confirm successful installation : python -m pip show pyjokes
 To run the program : python "C:\Python Activities\[Link]"

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.

7.1 String Operations

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

 Repetition: Repeat a string using the multiplication operator.


string * n
 Indexing: Access a character by its position (zero-based).
string[index]
 Length: Get the number of characters in a string.
len(string)

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

Example Sample Output and Explanation

first_name = "Alice" Alice Smith


last_name = "Smith"
How it works: It creates a new string that contains the
# Combining them with a space in between characters of the first string followed immediately by the
full_name = first_name + " " + last_name characters of the second.
print(full_name)
Note: You can only concatenate a string with another string. If
you try to add a string to an integer, Python will throw an error.

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

Example Sample Output and Explanation

echo = "Hello! " Hello! Hello! Hello!


# Repeat the string 3 times --------------------
result = echo * 3 How it works: You take a string and multiply it by an integer 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]

Example Sample Output and Explanation

P (The first character)


h (The fourth character)
n (The last character)
word = "Python"
How it works: You place the index number inside square brackets
[] after the string.
print(word[0])
print(word[3])
Reverse Indexing: Python also supports negative indexing. -1
print(word[-1])
refers to the last character, -2 to the second to last, and so on.

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)

Example Sample Output and Explanation

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

text1 = "Hello" Hello World


text2 = "World" 11

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.

7.2 String Slicing

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

 Slice range: Extract characters from start to stop


(stop excluded).
string[start:stop]
 Slice with step: Skip characters using a step value.
string[start:stop:step]
 Omit indices: Omitted start defaults to 0; omitted
stop defaults to end.
string[:stop], string[start:], string[::step]

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]

Example Sample Output and Explanation

text = "Python" Pyth


How it works: The format is string[start:stop]. The start index is
# From index 0 up to (but not including) 4 included, but the stop index is excluded.
print(text[0:4]) Logic: It effectively grabs characters from the start position up
to, but not including, the stop position.

2. Slice with Step


The step value allows you to skip characters within your defined range.

Basic Format
string[start:stop:step]

Example Sample Output and Explanation

numbers = "123456789" 13579


How it works: The format is string[start:stop:step]. The step
# Start at 0, end at 9, take every 2nd determines the increment between each index in the slice.
character Logic: A step of 2 takes every second character; a step of -1
print(numbers[0:9:2]) can be used to reverse a string.

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]

Example Sample Output and Explanation

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

# The base string Basic Range (0:6): Python


data = "Python_Programming_2026" Middle Slice (7:18): Programming
Negative Indexing (-4:): 2026
# 1. Basic Range: Extracting 'Python'
Slicing with Step (::2): Pto_rgamn_06
# Starts at 0, stops before 6
Reversed String (::-1):
basic_range = data[0:6]
print(f"Basic Range (0:6): {basic_range}") 6202_gnimmargorP_nohtyP

# 2. Middle Slice: Extracting 'Programming' Python


# Starts at 7, stops before 18 Logic: It grabs the first word perfectly because
middle_slice = data[7:18] "Python" is 6 characters long.
print(f"Middle Slice (7:18): {middle_slice}")
Programming
# 3. Negative Indexing: Extracting the year '2026' Logic: The length of the result is exactly 11
# Starts 4 characters from the end, goes to the very characters ($18 - 7 = 11$), which matches the
end length of the word "Programming."
negative_slice = data[-4:]
print(f"Negative Indexing (-4:): {negative_slice}") 2026
Logic: -4 refers to the 4th character from the end;
# 4. Slicing with Step: Skipping characters omitting the stop index tells Python to include
# Starts at the beginning, goes to the end, takes every everything from that point forward.
2nd character
step_slice = data[::2] Pto_Pormig22
print(f"Slicing with Step (::2): {step_slice}")
Logic: It picks the character at index 0, then 2,
# 5. Reversing the String then 4, and so on, until it reaches the end of the
# Uses a negative step to walk backward through the string.
entire string
reversed_string = data[::-1]
print(f"Reversed String (::-1): {reversed_string}")
6202_gnimmargorP_nohtyP

Logic: It starts at the last character and moves to


the first, effectively mirroring the text.

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

Method Purpose Example

find() Locate substring [Link]("a")

in Check existence "cat" in text

startswith() Test prefix [Link]("A")

isnumeric() Test numeric "123".isnumeric()

1. find(): Locate Substring

The find() method searches for a specific substring within a string and returns the lowest index where it is first
found.

Example Sample Output and Explanation

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.

2. in: Check Existence

The in operator is used to determine if a specific sequence of characters exists anywhere within a nother string.

Example Sample Output and Explanation

Is 'cat' in text? True


text = "The cat sat on the mat"
result = "cat" in text How it works: This is a membership operator that returns a Boolean value:
print(f"Is 'cat' in text? {result}") True if found, and False if not.
Explanation: Use this when you only need a "Yes" or "No" answer rather than
the exact position.

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.

Example Sample Output and Explanation

Starts with 'A'? True

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".

4. isnumeric(): Test Numeric Content

The isnumeric() method checks whether all characters in the string are numeric.

Example
Sample Output and Explanation

price = "1250" Is '1250' numeric? True Is '25 years' numeric? False

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]()}")

# The input string we are analyzing


Full String: 'ORD_9925 is pending'
order_data = "ORD_9925 is pending"
Starts with 'ORD'?: True
Is 'pending' in the text?: True
# 1. Using startswith() to check the prefix
Position of underscore: 3
is_order = order_data.startswith("ORD")
Is the ID part '9925' numeric?: True
# 2. Using 'in' to check for a specific keyword
is_pending = "pending" in order_data startswith("ORD"): This returns True because the very first
characters of our string match the prefix "ORD". It is perfect
# 3. Using find() to locate the underscore position for identifying data types.
underscore_pos = order_data.find("_") "pending" in order_data: This scans the entire string for the
word "pending". Since it exists toward the end, it returns the
# 4. Using isnumeric() on a slice of the string Boolean True.
# We extract the characters between the underscore and the space find("_"): This locates the underscore character. Since
order_number = order_data[4:8] indexing starts at 0 (O=0, R=1, D=2, _=3), it returns the
check_numeric = order_number.isnumeric() integer 3. If we searched for a character that didn't exist
(like "z"), it would return -1.
# Printing results isnumeric(): In this example, we combined slicing with
print(f"Full String: '{order_data}'") isnumeric(). We sliced the string to get "9925". Because that
print(f"Starts with 'ORD'?: {is_order}") substring contains only digits and no letters or spaces, it
print(f"Is 'pending' in the text?: {is_pending}") returns True.
print(f"Position of underscore: {underscore_pos}")
print(f"Is the ID part '{order_number}' numeric?: {check_numeric}")

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.

Basic syntax and how it works

 F-strings: Inline expressions inside curly braces.


f"Hello {name}"
 format method: Positional or named placeholders.
"Hello, {} {}".format(first, last)
 Percent formatting: Older style using specifiers.
"Price: %.2f" % value
1. F-Strings (Formatted String Literals)

Introduced in Python 3.6, f-strings are the most modern, readable, and fastest way to format strings.

Example Sample Output and Explanation



Next year, Alice will be 26 years old.
name = "Alice"
age = 25 The variable {name} is replaced by its value, and the expression
print(f"Next year, {name} will be {age {age + 1} is calculated and converted to a string automatically.
+ 1} years old.") How it works: You prefix the string with an f or F and place
variables or expressions inside curly braces {}.
Discussion: These are evaluated at runtime, meaning you can
even perform math or call methods directly inside the braces.
2. .format() Method

This method uses curly braces {} as placeholders within a string and fills them using the .format() function.

Example Sample Output and Explanation

first = "John" Hello, John Doe User: Admin, Status: Active

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.

Examples Sample Output and Explanation


item = "Apple" The Apple costs $1.99
price = 1.99
print("The %s costs $%.2f" % (item, price)) Explanation: %s acts as a placeholder for the string item.
%.2f acts as a placeholder for price and specifically rounds
the number to 2 decimal places.

How it works: It uses the % operator along with format


specifiers like %s (string), %d (integer), or %f (floating
point).
Discussion: It is often used for simple logging or when
working with older codebases. You can control decimal
precision using syntax like %.2f.

template = "{:<10} {:>8}" User Score


print([Link]("User", "Score"))
print([Link]("Ryan", 95)) Ryan 95

Creating the Template template = "{:<10} {:>8}"


 The string contains two placeholders, each defined
by curly braces {}.
 :<10: This instructs Python to left-align the text
and ensure the column is exactly 10 characters
wide. If the word is shorter than 10 characters,
Python fills the remaining space with blanks.
 :>8: This instructs Python to right-align the text
and ensure the column is exactly 8 characters
wide.
2. Printing the Header print([Link]("User",
"Score"))
 Python takes the string "User" and places it in the
first (left-aligned) column.
 It takes "Score" and places it in the second (right-
aligned) column.
3. Printing the Data print([Link]("Ryan", 95))
 Even though "Ryan" is shorter than "User," it stays
left-aligned.
 Even though 95 is an integer and "Score" is a
string, the template handles both, right-aligning
the number to stay perfectly under the "Score"
heading.

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.

Basic syntax and how it works


 Split by default: Split on whitespace into words.
[Link]()
 Split by delimiter: Split on a specific character or substring.
[Link](",")
 Join with separator: Combine list elements into one string.
" ".join(list_of_strings)
1. Split by Default

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.

Examples Sample Output and Explanation

['Learning', 'Python', 'is', 'fun']


sentence = "Learning Python is fun"
Even though there were two spaces between "is" and "fun,"
words = [Link]()
Python cleaned it up and returned four distinct words.
print(words)
How it works: It identifies any space, tab, or newline and uses it as
a boundary to cut the string.
Logic: Multiple spaces are treated as a single separator, and
leading/trailing whitespace is ignored.

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.

Examples Sample Output and Explanation

['Apple', 'Banana', 'Cherry', 'Date']


The comma acted as the "knife," resulting in a list of four separate
data = "Apple,Banana,Cherry,Date" items.
fruits = [Link](",")
print(fruits) How it works: Python looks for every occurrence of that specific
character and breaks the string at those points.
Logic: Unlike the default split, if there are two delimiters next to
each other, Python will return an empty string '' for that position.

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.

Sample Output and Explanation


Examples

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.

# Raw input data Step 1 (Default Split): ['User:Alex', ';',


raw_data = " User:Alex ; 'Hobbies:Hiking;Reading;Coding', ';', 'City:NewYork']
Hobbies:Hiking;Reading;Coding ; City:NewYork "
Step 2 (Delimiter Split): ['Hiking', 'Reading', 'Coding']
# 1. Split by Default (Clean up whitespace)
# This removes the leading/trailing spaces and splits Step 3 (Join): Alex's hobbies are Hiking, Reading,
into major chunks Coding.
chunks = raw_data.split()
print(f"Step 1 (Default Split): {chunks}") Split by Default ([Link]()): In the first step, split() was
used to break the long string into chunks based on the
# 2. Split by Delimiter (Extracting the hobbies) spaces. Because split() without arguments ignores
# We find the hobby section multiple spaces and trims the edges, it effectively
"cleaned" the raw input for us.
"Hiking;Reading;Coding" and split by the semicolon
Split by Delimiter ([Link](";")): In the second step,
hobby_section = chunks[2].split(":")[1] # Gets we focused on the hobby section. By using the semicolon
"Hiking;Reading;Coding" (;) as a delimiter, we told Python to ignore spaces and
hobby_list = hobby_section.split(";") only cut the string whenever it saw that specific symbol.
print(f"Step 2 (Delimiter Split): {hobby_list}") This converted a single string into a List of three separate
items: 'Hiking', 'Reading', and 'Coding'.
# 3. Join with Separator (Creating a clean sentence) Join with Separator (", ".join()): Finally, we used the join()
# We take the list and join it with a comma and a method to do the opposite of a split. We took our list of
space items and "glued" them back together using a comma and
formatted_hobbies = ", ".join(hobby_list) a space. Note that join() is called on the separator string,
and the list is passed into it as an argument.
print(f"Step 3 (Join): Alex's hobbies are
{formatted_hobbies}.")
data = "Math,Science,English" ['Math', 'Science', 'English']
subjects = [Link](",") Math | Science | English
print(subjects)
The program separates CSV data and reformats it for
final = " | ".join(subjects) display.
print(final)

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.

Introduction to Data Structures

1.1 Definition of a Data Structure

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.

Examples Sample Output and Explanation

Student Attendance List ['Ana', 'John', 'Mark', 'Liza']

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

customer = { The dictionary groups related data about one customer.


"name": "Carlos", This is a real-world scenario where banking systems
"balance": 3500, organize information efficiently.
"status": "Active"
}
print(customer["name"], customer["balance"])

1.2 Importance of Data Structures in Programming

Data structures are critical because they:

 Improve program efficiency


 Reduce code complexity
 Enable scalability
 Make programs easier to maintain and extend

137
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Examples Sample Output and Explanation

Order Processing System ['Order #1001', 'Order #1002']

orders = [] Without a data structure, managing thousands of orders


[Link]("Order #1001") would require excessive variables and code duplication.
[Link]("Order #1002")
print(orders)

Library Book Tracking Data Science

books = {"978-001": "Python Basics", "978- The dictionary enables instant lookup of books by their
002": "Data Science"} ISBN number.
print(books["978-002"])

1.3 Python’s Built-in Data Structures Overview

Python provides powerful built-in structures:

Structure Purpose

List Ordered, changeable sequence

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

students = ["Ana", "Ben", "Carlos"] Output


[Link]("Diana")
students[1] = "Brian" ['Ana', 'Brian', 'Carlos', 'Diana']
print(students)

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

location = (14.5995, 120.9842) (14.5995, 120.9842)


print(location)

The geographic coordinates remain constant throughout the program, ensuring


reliable reference data.
Output
config = ("[Link]", 8080, "active") ('[Link]', 8080, 'active')
print(config)

Tuples protect system configuration from being accidentally modified.

Dictionary Key-value storage

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

customer = {"name": "Alice", "balance": 4200, "status": "Active"}


print(customer)
print(customer["balance"])

Output

{'name': 'Alice', 'balance': 4200, 'status': 'Active'}


4200

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

A set stores unordered elements with no duplicates. Sets automatically remove


repeated values and support fast membership testing. Because order is not preserved,
sets are optimized for checking existence, filtering duplicates, and performing
mathematical set operations.

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.

Example Sample Output and Explanation

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.

Visualizing the Difference

Imagine you are looking for a specific book in a library:

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

2.1 Concept and Characteristics

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.

Ordered and Mutable Nature

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.

Indexing and Slicing

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.

Dynamic Resizing Behavior

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.

Basic List Format

list_name = [element1, element2, element3]

Example Student Enrolment System Sample Output and Explanation

students = ["Ana", "Ben", "Carlos"] All Students: ['Ana', 'Carlos', 'Diana']


First two students: ['Ana', 'Carlos']
# Adding a new student
[Link]("Diana")
A university registration system stores enrolled students in a list
# Removing a student that changes as students register or withdraw.
[Link]("Ben")
The list preserves the order of registration. It dynamically resizes
# Accessing and slicing when students are added or removed, and slicing allows
print("All Students:", students) retrieving subsets of the list efficiently.
print("First two students:", students[:2])
142
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Online Shopping Cart Sample Output and Explanation

cart = ["Laptop", "Mouse"] Shopping Cart: ['Laptop', 'Mouse', 'Keyboard', 'Headset']


Most recent item: Headset
[Link]("Keyboard")
[Link]("Headset")
An e-commerce platform stores selected products in a shopping cart
represented as a list.
print("Shopping Cart:", cart)
print("Most recent item:", cart[-1])
The shopping cart grows dynamically as customers add items. Indexing
allows quick access to any product, while the order reflects the sequence
of user actions.

2.2 List Operations and Methods

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

list_name = [item1, item2, item3]

Example

products = ["Laptop", "Mouse", "Keyboard"]

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.

Accessing and Updating Elements

List elements are accessed using their index position. Values can be updated directly.
Example
Sample Output and Explanation

products = ["Laptop", "Mouse", "Keyboard"] Laptop


print(products[0]) # Access ['Laptop', 'Monitor', 'Keyboard']
products[1] = "Monitor" # Update
print(products) The element at index 1 is replaced, demonstrating
the mutable nature of lists.
143
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Adding and Removing Elements

Python provides several built-in methods for modifying list contents.

Built-in Methods Output


append() — Add item at the end

cart = ["Phone", "Tablet"] ['Phone', 'Tablet', 'Charger']


[Link]("Charger")
print(cart)
extend() — Add multiple items

items = ["Pen", "Notebook"] ['Pen', 'Notebook', 'Eraser', 'Marker']


[Link](["Eraser", "Marker"])
print(items)
insert() — Add at a specific position

queue = ["Alice", "Charlie"] ['Alice', 'Bob', 'Charlie']


[Link](1, "Bob")
print(queue)
remove() — Delete by value

employees = ["Ana", "Ben", "Carlos"] ['Ana', 'Carlos']


[Link]("Ben")
print(employees)
pop() — Delete by index

tasks = ["Email", "Meeting", "Report"] ['Email', 'Report']


finished = [Link](1) Completed: Meeting
print(tasks)
print("Completed:", finished)
Reordering and Copying Lists

sort() — Arrange elements [60, 70, 85, 92]


scores = [85, 70, 92, 60]
[Link]()
print(scores)
reverse() — Reverse order

scores = [85, 70, 92, 60] [92, 85, 70, 60]


[Link]()
print(scores)
copy() — Duplicate list

original = ["Red", "Blue", "Green"] ['Red', 'Blue', 'Green']


backup = [Link]()
print(backup)

144
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example -
Sample Output and Explanation

Classroom Attendance System ['Ana', 'Diana', 'Carlos']

students = ["Ana", "Ben"]


[Link]("Carlos") The system dynamically adds, inserts, and removes
[Link](1, "Diana") students during class enrollment.
[Link]("Ben")
print(students)

Example
Sample Output and Explanation

# Initial warehouse stock Shipped out: Monitor


inventory = ["Keyboard", "Mouse", "Monitor"] Enter first new item to add: Camera
Enter second new item to add: Webcam
# 1. Removing the last item (e.g., it was shipped out)
Updated Warehouse Inventory:
removed_item = [Link]()
print(f"Shipped out: {removed_item}") ['Camera', 'Keyboard', 'Mouse', 'Webcam']

# 2. Taking user input for new arrivals


new_item1 = input("Enter first new item to add: ") Automatic Removal: The script immediately
new_item2 = input("Enter second new item to add: removes "Monitor" because [Link]() targets
") the last item in the list.

# 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.

Using for Loops

The for loop allows the program to visit each element in the list sequentially.

Basic Format

for item in list_name:


statement

Examples Sample Output and Explanation

Student Grade Processing Student score: 85


Student score: 90
grades = [85, 90, 78, 92] Student score: 78
Student score: 92
for grade in grades:
print("Student score:", grade) Each student’s grade is processed individually. This approach is widely
used in grading systems, attendance systems, and exam analysis
software.
Daily Sales Report
Total Sales: 4680
sales = [1200, 950, 1430, 1100] The loop computes the sum of daily transactions — a common
total = 0 operation in accounting and financial applications.

for amount in sales:


total += amount

print("Total Sales:", total)


Using Index-Based Iteration 0 Ana
1 Ben
Sometimes both the position and 2 Carlos
value are needed. len(names): This calculates the total number of items in your list (in this
case, 3).
names = ["Ana", "Ben", "Carlos"] range(3): This generates a sequence of numbers starting from 0 up to
(but not including) 3, which are 0, 1, 2.
for i in range(len(names)): names[i]: Inside the loop, i acts as the index. The code uses it to "point"
print(i, names[i]) to the specific item at that position in the list.

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

new_list = [expression for item in list]

Examples Sample Output and Explanation

Price Adjustment System [90.0, 180.0, 270.0]

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.

The Result: Python automatically creates a new list


named discounted and fills it with the results of
those calculations.
Filtering Passed Students [75, 82, 90]

scores = [75, 82, 60, 90, 68]


passed = [score for score in scores if score >= 70] This code is a List Comprehension with a Condition,
print(passed) used to filter data from an existing list based on a
specific rule.

Here is the breakdown of how it works:

 The Goal: It looks at the scores list and


creates a new list called passed that only
includes numbers greater than or equal to
70.
 The Filter: The if score >= 70 part acts like a
gatekeeper; if a score is lower than 70 (like
60 or 68), it is simply ignored and not added
to the new list.
 The Efficiency: Instead of writing a 4-line
loop with an if statement and an .append()
method, Python does everything in a single,
high-performance line.

147
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output and Explanation

A university registrar maintains a list of enrolled


--- Current Class List ---
students for each course. The system must handle
frequent updates such as adding new enrollees, 1 Ana
removing withdrawn students, and generating 2 Carlos
reports—all while keeping performance acceptable 3 Diana
as the class size grows. 4 Evan
Carlos is officially enrolled.
students = []

# 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])

# Searching for a student


search_name = "Carlos"
if search_name in students:
print("\n", search_name, "is officially enrolled.")
else:
print("\n", search_name, "is not enrolled.")

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

Total Sales: 3580.0


Average Sales: 1193.33
Code Highest Sale: 1430.0
Lowest Sale: 950.0

149
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Tuples (Immutable Sequences)

3.1 Concept and Characteristics

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.

Ordered but Immutable

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.

Differences between Lists and Tuples

Feature List Tuple

Mutable Yes No

Syntax [] ()

Performance Slightly slower Slightly faster

Safety Less secure More secure

Basic Format

tuple_name = (value1, value2, value3)

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

Data Integrity and Performance Advantages

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

Student Exam Record ('Ana', 85, 'Passed')

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.

3.2 Tuple Creation and Access

Examples Sample Output and Explanation

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.

status = ("Active",) Why the comma matters:

 ("Active"): Python sees this as just a String in parentheses (like


a math expression).
 ("Active",): The comma tells Python, "This is a Tuple containing
one item."

Indexing and Slicing 14.5


(14.5, 120.9)
location = (14.5, 120.9, "Manila")
print(location[0]) This code demonstrates how to access specific pieces of data within a
print(location[:2]) tuple using their position (index).

 Indexing (location[0]): This retrieves the single item at the very


first position, which is 14.5.
 Slicing (location[:2]): This extracts a "slice" or sub-section of the
tuple, starting from the beginning and stopping just before
index 2, resulting in a new tuple: (14.5, 120.9).

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.

Use as Dictionary Keys Manila

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.

Seat Reservation System Reserved


 The "Key" is a Coordinate: A seat in a theater or airplane is
seat = (5, "A") defined by two fixed pieces of information: a row (5) and a
reservations = {seat: "Reserved"} column ("A"). A tuple is the perfect structure to "bond" these
print(reservations[seat]) two values together.
 Immutability Requirement: As mentioned before, Python
dictionaries require keys to be immutable. Since the tuple (5,
"A") cannot be changed, it is allowed to serve as the unique
address for the value "Reserved".
 The Lookup: reservations[seat] tells Python to find the value
associated with the specific coordinate pair (5, "A").

System Configuration IP: [Link]


Management Port: 3306
Status: Running
config = ("[Link]", 3306,
"Running") This code demonstrates using a tuple to group database configuration
print("IP:", config[0]) settings. By using index numbers like [0], [1], and [2], you are pulling
print("Port:", config[1]) specific data points—the IP address, the port number, and the
print("Status:", config[2]) operational status—out of the immutable collection.

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

1. Create a tuple then, ask the user for the


Enter number of employees: 2
number of employees.
2. For each employee, input:
o Employee ID Employee 1
o Name Employee ID: 1001
o Department Name: Ana
o Hours Worked Department: IT
o Hourly Rate Hours Worked: 40
3. Store each employee’s information in a tuple. Hourly Rate: 250
4. Store all employee tuples in a collection for
processing. Employee 2
5. Use tuple unpacking to: Employee ID: 1002
o Display employee information
Name: Ben
o Compute and display salary
Department: HR
6. Display a structured payroll report.
Hours Worked: 38
Hourly Rate: 230
Code

--- PAYROLL REPORT ---

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)

4.1 Concept and Characteristics

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.

Examples Sample Output and Explanation

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

prices = { Keyboard price: 1500


"Laptop": 55000,
"Mouse": 700,
"Keyboard": 1500 Each product name acts as a key, enabling fast price
} lookup in retail systems.

print("Keyboard price:", prices["Keyboard"])

154
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
4.2 Dictionary Operations and Methods

Operations and Methods Output


Creating a Dictionary

employee = {"name": "Ana", "department": "IT"} {"name": "Ana", "department": "IT"}


Adding New Elements {'name': 'Ana', 'department': 'IT', 'age': 23}

employee["age"] = 23
print(employee)
Updating Existing Elements

employee["department"] = "HR" 'name': 'Ana', 'department': 'HR', 'age': 23}


print(employee)
Deleting Elements

Using del {'name': 'Ana', 'department': 'HR'}

del employee["age"]
print(employee)
Using pop()

[Link]("department") {'name': 'Ana'}


print(employee)
Clearing All Elements

[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

4.3 Iterating Through Dictionaries Ana


Ben
departments = {"Ana": "HR", "Ben": "IT", "Clara": Clara
"Sales"} HR
IT
for key in departments: Sales
print(key) Ana : HR
Ben : IT
for value in [Link](): Clara : Sales
print(value)
for key in departments: The default behavior; it only
for key, value in [Link](): prints the names (Ana, Ben, Clara).
print(key, ":", value)
for value in [Link](): Skips the names
and only prints the department titles (HR, IT, Sales).

for key, value in [Link](): Uses


"unpacking" to retrieve both the name and the
department as a pair in every step of the loop.
Inventory Management System
Enter item: Sugar
inventory = {"Rice": 20, "Sugar": 15, "Coffee": 10} Stock available: 15

item = input("Enter item: ")


if item in inventory: The Check (if item in inventory): This searches the
print("Stock available:", inventory[item]) keys of the dictionary. If you type "Rice", the
else: condition is true.
print("Item not found.")
The Access (inventory[item]): Once the item is found,
it uses the key to "unlock" and print the
corresponding number (the value).

The Safety Net (else): If the key doesn't exist (e.g.,


you type "Salt"), the program skips to the else block
rather than throwing a KeyError.

The dictionary allows instant stock lookup using item


names. This system mirrors real inventory tracking
used in retail stores.

156
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Example Sample Output and Explanation

# Create empty dictionary


students = {} === Student Record System ===
1. Add Student
while True: 2. Edit Student Grade
print("\n=== Student Record System ===") 3. Delete Student
print("1. Add Student") 4. View All Students
print("2. Edit Student Grade") 5. Search Student
print("3. Delete Student") 6. Exit
print("4. View All Students") Enter your choice: 1
print("5. Search Student") Enter student name: Anna
print("6. Exit")
Enter grade: 90
Student added successfully.
choice = input("Enter your choice: ")

if choice == "1": Enter your choice: 1


name = input("Enter student name: ") Enter student name: Mark
grade = int(input("Enter grade: ")) Enter grade: 85
students[name] = grade Student added successfully.
print("Student added successfully.")
Enter your choice: 4
elif choice == "2":
name = input("Enter student name to edit: ") Student Records:
if name in students: Anna : 90
new_grade = int(input("Enter new grade: ")) Mark : 85
students[name] = new_grade
print("Grade updated.")
Enter your choice: 2
else:
print("Student not found.") Enter student name to edit: Mark
Enter new grade: 88
elif choice == "3": Grade updated.
name = input("Enter student name to delete: ")
if name in students: Enter your choice: 5
[Link](name) Enter student name to search: Mark
print("Student deleted.") Grade: 88
else:
print("Student not found.") Enter your choice: 3
Enter student name to delete: Anna
elif choice == "4":
Student deleted.
if not students:
print("No records available.")
Enter your choice: 6
else:
print("\nStudent Records:") Program terminated.
for name, grade in [Link]():
print(name, ":", grade) This menu-based system continuously runs
elif choice == "5": until the user selects Exit. The dictionary
name = input("Enter student name to search: ")
grade = [Link](name) allows constant-time lookup for searching,
if grade is not None: updating, and deleting student records,
print("Grade:", grade) making it efficient for managing structured
else: data.
print("Student not found.")
elif choice == "6":
print("Program terminated.")
break
else:
print("Invalid choice. Try again.")

157
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity — Dictionary-Based Inventory Management System

Objective Sample Output

=== School Bookstore Inventory ===


At the end of this activity, the student should be able to:
1. Add Item
2. Update Item Quantity
• Apply dictionary operations in a real-world scenario
• Add, update, delete, and search data using dictionaries 3. Delete Item
• Use input statements to build an interactive program 4. View Inventory
• Demonstrate understanding of dictionary methods and 5. Search Item
performance behavior 6. Exit
Enter choice: 1
Problem Scenario Enter item name: Notebook
Enter quantity: 25
You are assigned to develop a simple Inventory Item added successfully.
Management System for a school bookstore.
The system must allow the user to: === School Bookstore Inventory ===
Enter choice: 1
1. Add new items Enter item name: Pen
2. Update existing item quantities
Enter quantity: 40
3. Remove items
Item added successfully.
4. Display all inventory records
5. Search for a specific item
=== School Bookstore Inventory ===
Instructions Enter choice: 4

1. Create an empty dictionary named inventory. Current Inventory:


2. Display a menu with the following options: Notebook : 25
o 1 — Add Item Pen : 40
o 2 — Update Item Quantity
o 3 — Delete Item === School Bookstore Inventory ===
o 4 — View Inventory Enter choice: 5
o 5 — Search Item Enter item to search: Pen
o 6 — Exit Stock: 40
3. The program must continuously run until the user
chooses Exit.
=== School Bookstore Inventory ===
4. All operations must use dictionary methods (add via
Enter choice: 3
assignment, update(), pop(), get(), etc.).
5. Validate inputs where necessary. Enter item to delete: Notebook
Item deleted.

=== School Bookstore Inventory ===


Enter choice: 6
Program terminated.

158
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Sets (Unique Collections)

5.1 Concept and Characteristics

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.

Basic Format How It Works

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.

5.2 Set Operations

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.

The most common operations include:

• Adding elements using add()


• Removing elements using remove() or discard()
• Membership testing using in
• Union (|) – combine elements from two sets
• Intersection (&) – find common elements
• Difference (-) – find elements in one set but not the other
• Symmetric difference (^) – elements in either set, but not both

159
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Set Operations in Python
1. Adding Elements — add()

The add() method inserts a new element into a set.


If the element already exists, the set remains unchanged because sets only store unique values.
This behavior automatically prevents duplicates, which is extremely useful in systems such as user registrations
or inventory tracking.

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.

2. Removing Elements — remove() and discard()

The remove() method deletes a specified element from a set.


If the element does not exist, it raises an error.
The discard() method performs the same task but does not raise an error if the element is missing, making it
safer for uncertain situations.

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

The in keyword checks whether an element exists inside a set.


This operation is extremely fast due to the internal hash-based structure of sets.
Membership testing is widely used in authentication systems, access control, and data validation.

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}.

# Create two sets representing students enrolled in Is John in Course A? True


two courses Union: {'Paul', 'Anna', 'Lisa', 'Kevin', 'John'}
course_A = {"Anna", "Mark", "John", "Lisa"} Intersection: {'John', 'Lisa'}
course_B = {"John", "Lisa", "Paul"} Difference (A - B): {'Anna', 'Kevin'}
Symmetric Difference: {'Anna', 'Kevin', 'Paul'}
# Adding elements
course_A.add("Kevin")
Modification Safety: .remove() will crash your
# Removing elements program if the name isn't there, whereas .discard() is
course_A.remove("Mark") # Removes an existing a "safe" delete that does nothing if the item is
element missing.
course_B.discard("Peter") # Does nothing if
element does not exist Set Operations:

# Membership testing  Union (|): Shows every student enrolled in


print("Is John in Course A?", "John" in course_A) at least one course.
 Intersection (&): Identifies "cross-enrolled"
# Set operations students (those taking both courses).
print("Union:", course_A | course_B)  Difference (-): Lists students only in Course A
print("Intersection:", course_A & course_B) (excluding those also in B).
print("Difference (A - B):", course_A - course_B)  Symmetric Difference (^): Lists students who
print("Symmetric Difference:", course_A ^ course_B) are in one course but not both (the opposite
of intersection).

162
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Examples Sample Output and Explanation

Student Club Membership System

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.

Website Access Control Enter username: alice


Access Granted
registered_users = {"alice", "bob", "charlie", "david"}
blocked_users = {"charlie"}
The program efficiently checks user access using
username = input("Enter username: ") membership testing. Sets provide fast lookup even
when the number of users becomes very large.
if username in registered_users and username not in
blocked_users:
print("Access Granted")
else:
print("Access Denied")

163
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Graded Activity — Event Registration Management Using Sets

Objective Sample Output

By completing this activity, the student should be able to:

• 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

6.1 Lists vs Tuples

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

shopping_list = ["Milk", "Eggs", "Bread"]


location = (10.5, 20.3)

Lists allow modification (append, remove), while tuples protect data from accidental change.

6.2 Dictionaries vs Sets

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

users = {"anna": "pass123", "mark": "abc456"}


logged_in_users = {"anna", "mark"}

6.3 Choosing the Right Data Structure

Choosing the right structure improves program clarity, speed, and reliability.
Ordered data → List or Tuple
Key-value relationships → Dictionary
Unique collections → Set

The correct choice reduces complexity and improves performance.

6.4 Performance Trade-offs

Structure Lookup Insert Delete Notes


List O(n) O(1)* O(n) Fast append, slow search
Tuple O(n) — — Immutable
Dictionary O(1) O(1) O(1) Fastest lookups
Set O(1) O(1) O(1) Excellent for membership tests

165
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Section 7 — Practical Applications and Case Studies

7.1 Data Management System

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']

Registered Emails: {'anna@[Link]', 'mark@[Link]'}


registered_emails.add("anna@[Link]")
registered_emails.add("mark@[Link]")

The dictionary provides fast customer ID lookup, the list keeps


[Link]("C001 bought Laptop")
transaction history in order, and the set ensures emails
[Link]("C002 bought Phone")
remain unique.
print("Customers:", customers)
print("Transactions:", transactions)
print("Registered Emails:", registered_emails)

7.2 Student Information System

Uses dictionaries for student profiles, lists for enrolled courses, and sets to prevent duplicate registrations.

Sample Output and Explanation


Example

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.

Example Sample Output and Explanation

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)

7.4 Social Media Data Processing

Uses sets for friend recommendations, dictionaries for profiles, and lists for activity feeds.

Sample Output and Explanation


Example

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

 Student ID (must never change) → use a Enter Name: Maria Cruz


tuple Enter Age: 19
 Student profile (name, age, course) → Enter Course: BSIT
use a dictionary
 Subjects enrolled → use a list Enter 3 subjects:
 Registered emails (no duplicates allowed) Subject 1: Programming
→ use a set Subject 2: Data Structures
Subject 3: Networking
Instructions
Enter 3 email addresses:
Write a Python program that will: Email 1: maria@[Link]
Email 2: maria@[Link]
Email 3: [Link]@[Link]
1. Ask the user for student information.
2. Store the student ID as a tuple.
----- STUDENT RECORD -----
3. Store the student profile in a dictionary.
Student ID: ('2025-019',)
4. Store multiple subjects in a list.
Profile: {'Name': 'Maria Cruz', 'Age': '19', 'Course': 'BSIT'}
5. Store email addresses in a set to avoid
Subjects: ['Programming', 'Data Structures', 'Networking']
duplicates.
Registered Emails: {'maria@[Link]', '[Link]@ [Link] }
6. Display the complete student record.

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.

Section 9.1 — Introduction to Sorting and Searching

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.

Section 9.2 — Sorting Algorithms

9.2.1 Bubble Sort


Bubble Sort is one of the simplest sorting algorithms and is often used for educational purposes. It works by
repeatedly comparing adjacent elements and swapping them when they are in the wrong order. Over multiple
passes through the list, the largest values gradually “bubble” up to the end of the list. Although easy to
understand and implement, Bubble Sort is inefficient for large datasets due to its quadratic time complexity.
Basic Format
for i in range(len(data)):
for j in range(len(data) - i - 1): How It Works
if data[j] > data[j+1]:
data[j], data[j+1] = data[j+1], data[j] The Outer Loop (for i in range(len(data))): This loop controls how
many passes the algorithm makes through the list. After each full
pass, the next largest element is guaranteed to be in its correct
final position.
The Inner Loop (for j in range(len(data) - i - 1)): This is where the
actual comparisons happen.
 The term - i is an optimization: since the last i elements
are already sorted, we don't need to check them again.
 The term - 1 prevents an "index out of bounds" error
when checking j+1.
The Swap (data[j], data[j+1] = data[j+1], data[j]): If the element
on the left is greater than the element on the right, Python swaps
their positions in a single line.
169
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Sample Output and Explanation
Examples

data = [5, 2, 8, 1] Sorted data: [1, 2, 5, 8]

# 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]

for i in range(len(sales)): The program repeatedly compares neighboring sales


for j in range(len(sales) - i - 1): values and swaps them when needed until all values
if sales[j] > sales[j+1]: are arranged in ascending order.
sales[j], sales[j+1] = sales[j+1], sales[j]

print("Sorted Sales:", sales)

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

--- SORTED STUDENT REPORT ---


S102 | Ben | Grade: 75
S101 | Ana | Grade: 88
S103 | Cara | Grade: 92
Code

173
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
9.3 — Searching Algorithms

9.3.1 Linear Search

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

for item in data:


if item == target:
found = True

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.

Sample Output and Explanation


Example

data = [3, 5, 7, 9] Initialization: The variable found is set to


target = 7 False because we haven't started looking yet.
The Traversal: The for loop looks at each
found = False # Initial state
number in data starting from index 0.
The Comparison:
# The loop traverses every item in the list  It checks 3: Not a match. found stays
for item in data: False.
if item == target:  It checks 5: Not a match. found stays
found = True False.
# In a real scenario, you could add 'break' here to stop early  It checks 7: Match! The code enters
the if block and sets found = True.
# Optional: print the status of each step to see it working The Final Step: Because there is no break
print(f"Checking {item}: Is it {target}? {'Yes' if item == target command, the loop checks 9 anyway. found
else 'No'}. Found is {found}") remains True.
The Result: Once the loop finishes, the
program prints the final status of the found
print("-" * 20) flag
print(f"Final Result: found is {found}")

174
Learning Module: Python Programming
Prepared by: Prof Ryan M. Agsaluna
ISUFST COT- Dumangas Campus
Examples Sample Output and Explanation

authorized_ids = [1001, 2045, 3099, 4022] Access Granted. Welcome back!


scanned_id = 3099
access_granted = False Input: The list of IDs is [1001, 2045, 3099, 4022] and the

for badge in authorized_ids: target is 3099.


if badge == scanned_id: Step 1: The loop checks 1001. Does 1001 == 3099? No.
access_granted = True
access_granted remains False.
if access_granted: Step 2: The loop checks 2045. Does 2045 == 3099? No.
print("Access Granted. Welcome back!")
else: access_granted remains False.
print("Access Denied. Unknown ID.") Step 3: The loop checks 3099. Does 3099 == 3099? Yes!
access_granted is updated to True.
Step 4: The loop checks the final ID 4022. No match, but
access_granted is already True.
inventory = ["Bread", "Eggs", "Milk", "Butter", "Cheese"] Yes, we have Milk available.
customer_request = "Milk"
Input: Inventory list ["Bread", "Eggs", "Milk", "Butter",
in_stock = False
"Cheese"] and target "Milk".
for item in inventory:
Step 1: Check "Bread". No match. in_stock is False.
if item == customer_request:
in_stock = True Step 2: Check "Eggs". No match. in_stock is False.
Step 3: Check "Milk". Match found! in_stock becomes
if in_stock:
print(f"Yes, we have {customer_request} available.") True
else:
print(f"Sorry, {customer_request} is out of stock.")
# Our "database" of contacts Enter the name to search for: Charlie
contacts = ["Alice", "Bob", "Charlie", "David", "Eve"]
Success: Charlie was found in your contacts.
# Input from the user Initial State: found is set to False.
target = input("Enter the name to search for: ")
Pass 1: The loop checks Alice. Comparison: "Alice" ==
found = False
"Charlie"? No.
# The Linear Search process
Pass 2: The loop checks Bob. Comparison: "Bob" ==
for name in contacts:
if [Link]() == [Link](): # .lower() makes it "Charlie"? No.
case-insensitive
Pass 3: The loop checks [Link]: "Charlie" ==
found = True
break # Optimization: stop searching once found "Charlie"? Yes!
Action: found becomes True and the break command
# Final Output
if found: ends the loop immediately.
print(f"Success: {target} was found in your contacts.")
Final Result: The program skips "David" and "Eve" and
else:
print(f"Error: {target} is not in your contact list.") prints the success message.

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

while low <= high:


mid = (low + high) // 2

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.

 (low + high): This adds the two boundary indices


together.
 // (Floor Division): This is a special type of
division in Python. It divides the numbers and
rounds down to the nearest whole number.
 2: We divide by two because we want to split the
list into two equal halves.

Example Sample Output and Explanation

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

print("Grade in system:", found)

A warehouse worker enters a Product ID to see if Enter Product ID: 1005


it is currently in the sorted inventory database.
Product 1005 is in stock.
product_ids = [1001, 1005, 1010, 1020, 1035,
1040, 1050, 1060]
Initial Range: low is 0, high is 7.
target = int(input("Enter Product ID: "))
First Mid: (0 + 7) // 2 = 3. product_ids[3] is 1020.
low = 0
Comparison: 1020 is greater than 1005. The target must be to the
high = len(product_ids) - 1
found = False left.
New Range: high becomes mid - 1 (2). low remains 0.
while low <= high:
mid = (low + high) // 2 Second Mid: (0 + 2) // 2 = 1. product_ids[1] is 1005.
if product_ids[mid] == target:
Match: 1005 matches the target! found becomes True.
found = True
break
elif product_ids[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

Bubble Sort, Selection Sort, Linear Search, Binary Search

Student Record Management and Search 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

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: Student 1
o Student Name Name: Ana
o Student ID ID: S102
o Final Grade (integer) Final Grade: 88
4. Ask the user to choose which sorting algorithm to use:
o 1 — Bubble Sort Student 2
o 2 — Selection Sort Name: Ben
5. Apply the selected sorting algorithm to sort students by ID. ID: S101
6. Display the sorted student list. Final Grade: 75
7. Ask the user for a Student ID to search.
8. Perform a Binary Search on the sorted list. Student 3
Name: Cara
9. Display whether the student is found and show the
ID: S103
student’s full record.
Final Grade: 92
Code
Choose Sorting Algorithm
1 - Bubble Sort
2 - Selection Sort
Enter choice: 2

Enter Student ID to search: S102

--- SORTED STUDENT LIST ---


S101 - Ben - Grade: 75
S102 - Ana - Grade: 88
S103 - Cara - Grade: 92

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

Total Score: 20 Points

Criteria Excellent Good Satisfactory Needs Improvement


5 pts — Program runs 4 pts — Minor 1–2 pts — Program
Program 3 pts — Some
correctly and meets all errors but mostly fails to meet major
Functionality (5 pts) features incorrect
requirements correct requirements
Algorithm 5 pts — Sorting/searching
4 pts — Minor 3 pts — Partial or 1–2 pts — Incorrect
Implementation (5 logic is correct and
logical issues inefficient logic or missing algorithms
pts) efficient
4 pts — Proper and
2 pts — Limited
Use of Data effective use of lists, 3 pts — Mostly 1 pt — Incorrect
or inconsistent
Structures (4 pts) dictionaries, sets, and correct use structure usage
use
tuples
3 pts — Clear input flow;
Input & Output 2 pts — Minor 1 pt — Basic 0 pts — Poor or
formatted, user-friendly
Handling (3 pts) formatting issues formatting only confusing output
output
Code Organization & 3 pts — Clean, readable 2 pts — Mostly 1 pt — Some
0 pts — Disorganized
Documentation (3 code with helpful organized with structural issues,
and undocumented
pts) comments some comments few comments

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

You might also like