3 Control Flow Explained
Key Concepts
Control flow in Python refers to the order in which statements are executed in a program. The three primary control flow structures are:
- Conditional Statements (
if
,elif
,else
) - Loops (
for
,while
) - Control Flow Statements (
break
,continue
,pass
)
1. Conditional Statements
Conditional statements allow you to execute different blocks of code based on certain conditions. The primary keywords used are if
, elif
, and else
.
Example:
age = 18 if age < 18: print("You are a minor.") elif age == 18: print("You just turned 18!") else: print("You are an adult.")
Think of conditional statements as a decision tree where each branch represents a different outcome based on the condition.
2. Loops
Loops allow you to execute a block of code repeatedly. Python provides two main types of loops: for
loops and while
loops.
Example of a for
loop:
for i in range(5): print("Iteration:", i)
Example of a while
loop:
count = 0 while count < 5: print("Count:", count) count += 1
Think of loops as a merry-go-round where the code block keeps executing until a certain condition is met.
3. Control Flow Statements
Control flow statements allow you to alter the normal flow of a loop. The primary keywords used are break
, continue
, and pass
.
Example using break
:
for i in range(10): if i == 5: break print(i)
Example using continue
:
for i in range(10): if i % 2 == 0: continue print(i)
Example using pass
:
for i in range(5): if i == 3: pass # Placeholder for future code print(i)
Think of control flow statements as traffic signals that direct the flow of your code, allowing you to skip certain parts or exit early.
Putting It All Together
By understanding and using conditional statements, loops, and control flow statements, you can create dynamic and responsive Python programs. These structures allow you to make decisions, repeat tasks, and control the flow of your code efficiently.
Example:
user_input = input("Enter a number: ") number = int(user_input) if number < 0: print("Negative number detected.") else: for i in range(number): if i == 3: continue print("Count:", i) if i == 7: break
In this example, the program takes user input, checks if it's negative, and then iterates through the numbers, skipping 3 and stopping at 7.