micheledpierri.com

Control Flow: Conditions and Loops

Lesson Objectives

By the end of this lesson, you will be able to:

  • Write conditional logic using if, elif, and else
  • Iterate over ranges of values using for loops
  • Control execution with while loops
  • Understand why control flow is fundamental for data processing and modeling

This lesson marks a transition:

Python stops being declarative and starts being algorithmic.


What Is Control Flow

Control flow defines how code executes:

  • which instructions run
  • when they run
  • how many times they run

Without control flow, programs would execute linearly and be almost useless for real data.


Conditional Statements (if, elif, else)

Basic Structure

age = 20

if age >= 18:
    print("Adult")
else:
    print("Minor")

​How it works:

  • the condition after if is evaluated
  • if True, the indented block runs
  • otherwise, the else block runs

Multiple Conditions (elif)

score = 75

if score >= 90:
    print("Excellent")
elif score >= 60:
    print("Passed")
else:
    print("Failed")

Only one branch is executed.


Boolean Expressions

Conditions rely on boolean expressions.

Common Operators

==   equal
!=   not equal
>    greater than
<    less than
>=   greater or equal
<=   less or equal

​Example:

x = 10
print(x > 5)   # True

​These expressions are everywhere in data filtering and decision rules.


Indentation Is Not Optional

Python uses indentation, not braces.

if x > 0:
    print("Positive")
    print("Still inside if")

​Incorrect indentation causes errors or logical bugs.

Rule:

Indentation defines program structure.


5️⃣5️⃣5️⃣for Loops

for loops are used to iterate over sequences.

Basic Example

for i in range(5):
    print(i)

​Output:

0
1
2
3
4

​range(5) generates numbers from 0 to 4.

Custom Ranges

for i in range(1, 6):
    print(i)

​Output:

1
2
3
4
5

​This pattern is extremely common in simulations and analyses.


while Loops

while loops run as long as a condition is True.

x = 0

while x < 5:
    print(x)
    x += 1

Important:

  • you must update the condition
  • otherwise, you create infinite loops

Choosing Between for and while

General rule:

  • use for when you know how many iterations you need
  • use while when the stopping condition is dynamic

In data analysis:

  • for → iterating over datasets
  • while → iterative algorithms and convergence

Control Flow in Data Analysis

Control flow enables:

  • filtering observations
  • conditional transformations
  • iterative model fitting
  • simulations and bootstrapping

Almost every analytical pipeline depends on it.


FAQ — Frequently Asked Questions

Q: Why does Python not use {} like other languages?

A: Python prioritizes readability and enforces indentation-based structure.

Q: Can I nest if statements?

A: Yes, but excessive nesting reduces readability.

Q: Is for slower than vectorized operations?

A: Often yes. Loops are foundational, but later we’ll optimize.

Q: What happens if a condition is always True?

A: In a while loop, the program never stops.


Exercises

Exercise 1

Write an if statement that checks if x is positive.

Exercise 2

Write an if/else that checks if a number is even or odd.

Exercise 3

Use elif to classify a score (fail/pass/excellent).

Exercise 4

Print numbers from 0 to 9 using a for loop.

Exercise 5

Print numbers from 1 to 10.

Exercise 6

Use a while loop to print numbers from 0 to 4.

Exercise 7

Predict the output:

x = 3
if x > 5:
    print("A")
else:
    print("B")

​Exercise 8

Explain why this code is wrong:

while x < 10:
print(x)

​Exercise 9

Write a loop that sums numbers from 1 to 5.

Exercise 10

Explain why control flow is essential in data analysis.


Solutions

Exercise 1

if x > 0:
    print("Positive")

Exercise 2

if n % 2 == 0:
    print("Even")
else:
    print("Odd")

​Exercise 3

if score >= 90:
    print("Excellent")
elif score >= 60:
    print("Passed")
else:
    print("Failed")

​Exercise 4

for i in range(10):
    print(i)

​Exercise 5

for i in range(1, 11):
    print(i)

​Exercise 6

x = 0
while x < 5:
    print(x)
    x += 1

​Exercise 7

# Output: B

​Exercise 8

# Indentation error: the print statement must be indented

​Exercise 9

total = 0
for i in range(1, 6):
    total += i
print(total)

​Exercise 10

# Control flow allows decisions, iteration, and conditional data processing

​Next Lesson Preview

In Lesson 6, we will introduce:

  • functions
  • parameters and return values
  • why functions are essential for reusable analytical pipelines

This is where Python code becomes modular and scalable.