Control Flow

Making Decisions and Repeating Actions

Control flow statements are the decision-making and repetition mechanisms of a programming language. They allow your program to execute different pieces of code based on certain conditions or to repeat actions a specific number of times.

The if, elif, and else Statements

This is the most fundamental conditional statement. It lets you execute a block of code only if a condition is true.

  • if: Starts the block. The condition is evaluated. If True, the indented code under it runs.
  • elif (short for "else if"): An optional block. If the first if is False, this condition is checked. You can have multiple elif blocks.
  • else: An optional block that runs if all preceding if and elif conditions were False.
Start
if condition?
True
Run "if" block
False
elif condition?
True
Run "elif" block
False
Run "else" block
age = 18
has_permission = False

if age >= 18 and has_permission: print("Access granted.") elif age >= 18 and not has_permission: print("You are old enough, but need permission.") else: print("Access denied. You are too young.")

Truthiness and Falsiness: In Python, it's not just True and False. Other values are considered "truthy" or "falsy" in a boolean context.

  • Falsy values: False, None, zero of any numeric type (0, 0.0), and any empty sequence ("", [], ()) or collection ({}).
  • Truthy values: Everything else! Any non-empty string, non-zero number, or non-empty collection is considered True.

The while Loop

The while loop executes a block of code as long as its condition remains true. It's ideal when you don't know in advance how many times you need to loop.

Start
while condition?
True
Run loop body
False
End
# Countdown from 5
count = 5
while count > 0:
    print(count)
    count -= 1 # This is crucial to avoid an infinite loop
print("Blast off!")

You can use break to exit a loop immediately and continue to skip the current iteration and jump to the top of the loop.

The for Loop

The for loop is used for iterating over a sequence (like a list, tuple, dictionary, set, or string). This is called a "for-each" loop in some other languages.

Start
Get next item from sequence
More items?
True
Run loop body
False
End
# Looping through a list
for fruit in ["apple", "banana", "cherry"]:
    print(f"I like {fruit}s")

Looping through a string

for char in "Python": print(char, end='-') # P-y-t-h-o-n-

The range() function is a common partner for for loops. It generates a sequence of numbers.

  • range(stop): Goes from 0 up to (but not including) stop.
  • range(start, stop): Goes from start up to stop.
  • range(start, stop, step): Goes from start to stop, incrementing by step.

Looping with else

A unique feature in Python is that loops can have an else block. This block executes only if the loop completes its entire sequence without being terminated by a break statement.

# Search for a number in a list
my_list = [1, 5, 9, 13]
search_for = 7

for num in my_list: if num == search_for: print("Found the number!") break else: # This runs only if the loop finishes without a 'break' print("The number was not in the list.")