LECTURE NOTE: Control Flow & Statements
Prerequisites:
- Understanding
of Python variables, indentation, and basic data types (integers, strings,
lists). Familiarity with basic input/output operations and simple
expressions.
What You’ll Be Able to Do:
·
Explain how control flow determines the logical sequence of
program execution.
·
Build programs using conditional statements, loops, and functions.
·
Apply modular programming concepts to organize code efficiently.
Introduction: What Is Control Flow and Why Should You Care?
Core Definition
·
Control flow defines the order in which individual statements,
instructions, or functions are executed within a program. In Python, control
flow is governed primarily by conditional statements, loops, and function
calls. Together, they determine how your program reacts to conditions, repeats
actions, and organizes logic into reusable parts.
·
Control flow transforms a program from a simple top-to-bottom
script into a dynamic decision-making system. Without it, programs could only
execute one static sequence of instructions no choices, no repetition, no
structure.
A Simple Analogy
Imagine a
chef following a recipe.
·
If the sauce is too thick → add water.
·
Else → serve it.
·
Repeat until all dishes are done.
·
Each decision and repetition represents a control flow statement.
Limitation:
- This
analogy works for understanding how programs “decide” and “repeat,” but it
doesn’t fully capture how code can branch and return results across
multiple functions or files.
Why This Matters to You
Problem It Solves:
- Without
control flow, every task in a program would have to be hard-coded. You
couldn’t check user input, repeat operations, or structure large projects
efficiently.
What You’ll Gain:
Decision Power: Write
programs that think — make logical choices based on data.
Automation Skills: Perform
repetitive tasks automatically using loops.
Code Organization: Structure
your programs using functions and modules for readability and reuse.
Real-World Context:
- Control
flow drives everything from login systems (checking user credentials) to
recommendation algorithms and automation scripts in data science.
The Foundation: Core Concepts Explained
We’ll break down the five key
building blocks:
Concept A: Conditional
Statements
Definition:
- Conditional
statements allow a program to execute different blocks of code depending
on whether a condition evaluates to True or False. Python uses the
keywords if, elif, and else.
Key Characteristics:
·
A condition is any Boolean expression (True/False).
·
Indentation defines which statements belong to the condition.
·
Only one block among if/elif/else executes per decision chain.
Example:
age = 20if age >= 18: print("Eligible to vote.")else: print("Not eligible.")
Common
Confusion:
·
Beginners often confuse = (assignment) with == (comparison).
Remember:
·
= assigns a value.
·
== compares two values.
Concept B: If/Else and Nested
Conditions
Definition:
- if/else
statements decide between two or more outcomes. You can chain multiple
conditions using elif (else if). Nested conditions occur when an if block
contains another if statement inside it.
How It Relates to Concept A:
- While
“conditional statements” define the general concept, if/else are the
specific Python tools to implement them.
Key Characteristics:
·
if checks the first condition.
·
elif handles secondary possibilities.
·
else executes only if none of the previous conditions are true.
Example:
score = 85if score >= 90: print("Excellent")elif score >= 75: print("Good")else: print("Needs Improvement")
Remember:
- Conditions
are evaluated top to bottom; once one is true, the rest are skipped.
Concept C: Loops
Definition:
- Loops
are used to repeat a block of code multiple times until a condition
changes. Python supports for loops and while loops.
Key Characteristics:
·
for loops iterate over sequences (like lists or ranges).
·
while loops run while a condition remains true.
·
Loops can be controlled using break (to exit) and continue (to
skip).
- New
programmers sometimes forget to update the loop condition in while loops,
causing infinite loops. Always ensure the condition eventually becomes
false.
Concept D: Functions
Definition:
- A
function is a reusable block of code that performs a specific task. It can
accept inputs (parameters) and return outputs (values).
Key Characteristics:
·
Defined using def keyword.
·
Helps keep code organized and reusable.
·
Returns results using return.
Example:
def greet(name): return f"Hello, {name}!" print(greet("Amit"))
Remember:
- Functions
follow the DRY principle — Don’t Repeat Yourself.
Concept E: Modules
Definition:
- Modules
are files containing Python code (functions, variables, or classes) that
can be imported into other programs. They help organize and reuse logic
across multiple files.
Key Characteristics:
·
Use import to access.
·
Built-in modules include math, os, and datetime.
·
Custom modules can be created by saving Python files with .py
extension.
Example:
helpers.py def add(a, b): return a + b main.py import helpersprint(helpers.add(5, 3))
Common
Confusion:
- Import
errors usually occur due to file misplacement or incorrect naming.
How They Work Together
- Conditional
statements make choices, loops perform repetition, functions encapsulate
logic, and modules organize it all.
Think of it like this:
·
Conditionals = decisions
·
Loops = persistence
·
Functions = delegation
·
Modules = teamwork
Seeing It in Action: Worked Examples
Example 1: Simple
Conditional
Scenario:
- A
program checks if a number is positive, negative, or zero.
Approach:
- We’ll
use if/elif/else to control the decision path.
num = 5if num > 0: print("Positive number")elif num == 0: print("Zero")else: print("Negative number")
Output:
- Positive
number
Explanation:
- The
program evaluates each condition in order. Only the first true condition
runs.
Check Your Understanding:
- What
happens if num = 0? Which block executes?
Example 2: Loop
with Conditional
Scenario:
- Print
all even numbers between 1 and 10.
Approach:
- Use
a loop to iterate and an if-statement to check evenness.
for i in range(1, 11): if i % 2 == 0: print(i)
Output:
246810
Key
Lesson:
- Combining
loops and conditionals allows selective repetition.
Example 3: Using
Functions and Loops Together
Scenario:
- A
store wants to calculate total bill with discount logic.
Approach:
- Encapsulate
logic in a function and use loops to handle multiple items.
def apply_discount(price_list, discount): total = 0 for price in price_list: total += price return total - (total * discount / 100) items = [200, 150, 100]print("Final Bill:", apply_discount(items, 10))
Output:
Final Bill: 405.0
What
Happened:
- The
function sums up prices and applies a 10% discount — reusable, clean, and
efficient.
Example 4: Real-World
Use — Temperature Monitoring System
Background:
- A
data logger needs to classify temperature readings into categories.
Challenge:
- Automate
the classification of readings from a sensor.
Approach:
- Use
functions, conditionals, and loops.
def classify_temp(temp): if temp < 15: return "Cold" elif temp <= 30: return "Moderate" else: return "Hot" temps = [10, 22, 35]for t in temps: print(f"Temperature {t}°C is {classify_temp(t)}")
Output:
Temperature 10°C is ColdTemperature 22°C is ModerateTemperature 35°C is Hot
Why
This Works:
- It
uses modular and conditional logic, scalable for any dataset.
Common Pitfalls: What Can Go Wrong
Mistake 1: Using
= instead of == in comparisons
Problem: Code
assigns instead of compares, leading to logical errors.
Right Approach: Always
use == for equality checks.
Why It Works: Ensures
the condition evaluates a Boolean expression.
Mistake 2: Infinite
Loops
Problem: Missing
condition update keeps loop running forever.
Right Approach: Modify
loop variables or use break when necessary.
Why It Works: Prevents
the condition from staying True indefinitely.
Mistake 3: Indentation
Errors
Problem: Python
depends on indentation; misalignment causes IndentationError.
Right Approach: Use
consistent 4-space indentation.
Why It Works: Python
uses whitespace to define logical blocks.
Mistake 4: Forgetting
return in functions
Problem: Function
outputs None unexpectedly.
Right Approach: Always
include return when you expect an output.
Why It Works: return
explicitly passes results back to the caller.
Your Turn: Practice & Self-Assessment
Challenge:
·
Create a Python script that:
·
Takes user input for marks in 3 subjects.
·
Calculates the average.
·
Uses conditionals to print a grade (A, B, C, or Fail).
·
Uses a function to encapsulate logic.
Hint:
- Use
if/elif/else for grading and def for modularity.
Extension:
- Save
the function in a module and import it into a main program.
Check Your Understanding:
·
Explain in your own words how while differs from for loops.
·
You encounter code using nested if statements — when might this be
better replaced with elif?
Identify the error:
if x = 5: print("Match")
What’s
wrong, and how do you fix it?
How could you use a function to
avoid repeating code that prints results?
Answers & Explanations:
·
for loops iterate over sequences; while depends on a changing
condition.
·
When multiple exclusive conditions exist, elif prevents
unnecessary nesting.
·
= should be ==. Assignment isn’t valid in a condition.
Define a function and call it
whenever needed — promotes reuse and clarity.
Self-Assessment Checklist
✅ Explain
if/else, loops, and functions clearly. ✅ Recognize where to apply conditionals or loops in real problems. ✅ Avoid infinite loops and logical mistakes. ✅ Write clean, modular code using functions. ✅ Use modules for structure and reuse.
- If
fewer than 5 boxes are checked — revisit examples on conditionals and
loops.
Consolidation: Key Takeaways & Next Steps
The Essential Ideas:
Control Flow: Directs
how code executes.
Conditionals: Enable
decisions.
Loops: Enable
repetition.
Functions: Enable
reuse.
Modules: Enable
organization.
Mental Model Check:
- Think
of control flow as the “brain” of your program — deciding what to do,
when, and how often.
What You Can Now Do:
- You
can write dynamic Python programs that make decisions, repeat actions
efficiently, and stay well-organized through modular design.
Next Steps:
·
Experiment with nested loops and complex conditions.
·
Practice writing small utility modules.
·
Explore built-in modules like math, datetime, and random.