Python Chapter 3: Flow Control

Master Conditional Logic, Loops, and Program Flow

Introduction to Flow Control

Flow control statements allow your program to make decisions and repeat actions. They are the building blocks of program logic, enabling your code to respond to different conditions and process data efficiently.

Key Concepts Covered

  • Conditional Statements: if, elif, else - Make decisions based on conditions
  • Comparison Operators: ==, !=, <, >, <=, >= - Compare values
  • Logical Operators: and, or, not - Combine conditions
  • While Loops: Repeat code while a condition is true
  • For Loops: Iterate over sequences with range()
  • Loop Control: break, continue, and pass statements
  • Loop-Else: Execute code when loops complete normally
  • Truthy/Falsy: Understanding boolean evaluation

Conditional Statements (if/elif/else)

Conditional statements allow your program to execute different code blocks based on whether conditions are true or false.

# Basic if statement if temperature > 30: print("It's hot outside!") # if-else statement if age >= 18: print("You can vote") else: print("You cannot vote yet") # if-elif-else statement if score >= 90: grade = "A" elif score >= 80: grade = "B" elif score >= 70: grade = "C" else: grade = "F"
Key Point: Python uses indentation (usually 4 spaces) to define code blocks. All statements at the same indentation level belong to the same block.

Comparison and Logical Operators

Comparison Operators

==Equal to
!=Not equal to
<Less than
>Greater than
<=Less than or equal
>=Greater than or equal

Logical Operators

andBoth conditions must be True
orAt least one condition must be True
notReverses the boolean value
# Using logical operators if age >= 18 and has_license: print("You can drive") if is_weekend or is_holiday: print("Time to relax!") if not is_raining: print("Let's go for a walk")

Loops: While and For

While Loops

Execute code repeatedly while a condition is true.

# Basic while loop count = 0 while count < 5: print(count) count += 1 # While with break while True: user_input = input("Enter 'quit' to exit: ") if user_input == "quit": break # While with continue i = 0 while i < 10: i += 1 if i % 2 == 0: continue # Skip even numbers print(i)

For Loops

Iterate over sequences using the range() function.

# Basic for loop for i in range(5): print(i) # Prints 0, 1, 2, 3, 4 # Range with start and stop for i in range(1, 6): print(i) # Prints 1, 2, 3, 4, 5 # Range with step for i in range(0, 10, 2): print(i) # Prints 0, 2, 4, 6, 8 # Nested loops for i in range(3): for j in range(3): print(f"i={i}, j={j}")

Special Loop Features

Loop-Else Clause

The else clause executes when a loop completes normally (without hitting a break statement).

# For-else example for n in range(2, 10): for x in range(2, n): if n % x == 0: print(f"{n} is not prime") break else: print(f"{n} is prime")

The Pass Statement

A null operation that does nothing. Used as a placeholder.

# Using pass as placeholder if condition: pass # TODO: implement this later else: handle_error()

Truthy and Falsy Values

In Python, many values can be evaluated as True or False in boolean contexts.

# Falsy values: False, None, 0, 0.0, "", [], {}, () # Everything else is truthy items = [] if not items: # Empty list is falsy print("No items") name = "Alice" if name: # Non-empty string is truthy print(f"Hello, {name}")

Interactive Flowchart Visualizer

Visualize how conditional statements flow through different execution paths. Select a code example and step through the execution.

Code Example

Loop Simulator

Step through loop execution to see how variables change and understand loop behavior.

Variables

Output

Condition Builder

Build complex conditions by dragging and dropping operators and values. See how they evaluate in real-time.

Components

Click to add to workspace

Variables
age
score
temp
Comparison
>=
>
<
==
Logical
and
or
not
Values
18
100
True

Build Your Condition

Click components from the palette to build a condition

Result

Quick Reference Guide

if Statement Syntax

if condition: # code block elif condition: # code block else: # code block

while Loop Syntax

while condition: # code block if exit_condition: break if skip_condition: continue

for Loop Syntax

for var in range(start, stop, step): # code block # range(5) → 0,1,2,3,4 # range(2,7) → 2,3,4,5,6 # range(0,10,2) → 0,2,4,6,8

Comparison Operators

==Equal to
!=Not equal to
<Less than
>Greater than
<=Less than or equal to
>=Greater than or equal to

Logical Operators

andTrue if both are True
orTrue if at least one is True
notReverses the boolean

Truthy and Falsy Values

Falsy Values:
  • False, None
  • 0, 0.0
  • "" (empty string)
  • [], {}, () (empty collections)
Truthy Values:

Everything else!

Loop Control

breakExit the loop immediately
continueSkip to next iteration
passDo nothing (placeholder)

Loop-Else Clause

for item in items: if found: break else: # Runs if no break

Common Patterns

Input Validation Loop

while True: user_input = input("Enter a positive number: ") if user_input.isdigit() and int(user_input) > 0: number = int(user_input) break print("Invalid input. Try again.")

Counting Loop

count = 0 for item in items: if item > 10: count += 1 print(f"Found {count} items greater than 10")

Finding an Item

for item in items: if item == target: print(f"Found {target}!") break else: print(f"{target} not found")

Test Your Knowledge

Answer the following questions to test your understanding of Python flow control.

Your Score
0 / 10
Course Home