Python Primer — Module 7: Control Flow
Welcome to Module 7 of our Python Primer series. In this module, we’ll explore how to direct the flow of a Python program using conditional statements and loops. Understanding control flow is crucial for building programs that can make decisions and repeat operations based on those decisions. We’ll cover the syntax and use cases of if, else, elif, for, and while statements, including how to control their execution flow with break, continue, and pass.
Conditional Statements
Conditional statements allow your program to execute certain pieces of code based on conditions or decisions.
The if Statement
The if statement executes a block of code only if a specified condition is true.
age = 20
if age >= 18:
print("You are an adult.")
# Outputs: You are an adult.The else and elif Statements
else complements the if statement and executes a block of code when the if condition is false. elif (else if) allows you to check multiple expressions for True and execute a block of code as soon as one of the conditions evaluates to True.
age = 16
if age >= 18:
print("You are an adult.")
elif age < 18 and age >= 13:
print("You are a teenager.")
else:
print("You are a child.")
# Outputs: You are a teenager.Nested Conditional Statements
You can nest if statements within each other to check further conditions if a condition is true.
age = 20
if age > 12:
if age < 20:
print("You are a teenager.")
else:
print("You are an adult.")
# Outputs: You are an adult.Loops
Loops allow you to execute a block of code multiple times.
The for Loop
The for loop is used for iterating over a sequence (list, tuple, dictionary, set, or string).
for i in range(5):
print(i)
# Outputs: 0, 1, 2, 3, 4You can also loop through data structures:
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Outputs: apple, banana, cherryThe while Loop
The while loop repeats as long as a certain boolean condition is met.
count = 1
while count < 6:
print(count)
count += 1
# Outputs: 1, 2, 3, 4, 5Loop Control Statements
break: Exits the loop entirely.continue: Skips the current iteration of the loop and moves to the next iteration.pass: Acts as a placeholder for future code.
for num in range(10):
if num == 5:
break # Breaking the loop when num is 5
if num % 2 == 0:
continue # Continuing to the next iteration if num is even
print(num)
# Outputs: 1, 3Conclusion
In this module, you’ve learned how to manage the flow of a Python program using conditional statements and loops. These structures are essential for creating programs that can make decisions, perform tasks repeatedly, and handle different data and inputs efficiently.
Get BitWiser’s stories in your inbox
Join Medium for free to get updates from this writer.
Stay tuned for our next module where we’ll explore functions in Python, enabling you to write reusable blocks of code that perform specific tasks.






