Control Flow: Guiding the Execution Path
Control flow dictates the order in which instructions are executed within a program. Python offers constructs like conditional statements and loops to manage this flow.
1. Conditional Statements: Making Decisions
if-elif-else
Statement: Allows your program to branch execution based on conditions.
graph LR A[Start] --> B{Condition 1 True?} B -- Yes --> C[Execute Block 1] B -- No --> D{Condition 2 True?} D -- Yes --> E[Execute Block 2] D -- No --> F[Execute 'else' Block] C --> G[End] E --> G F --> G
1x = 10
2
3if x > 15:
4 print("x is greater than 15")
5elif x > 5:
6 print("x is greater than 5 but not greater than 15")
7else:
8 print("x is less than or equal to 5")
2. Loops: Repeating Code Blocks
for
Loop: Iterates over a sequence (like a list or string).
graph LR A[Start] --> B{For each item in sequence} B -- Yes --> C[Execute Loop Body] C --> B B -- No --> D[End]
1fruits = ["apple", "banana", "cherry"]
2for fruit in fruits:
3 print(fruit)
while
Loop: Repeats a block of code as long as a condition holds true.
graph LR A[Start] --> B{Condition True?} B -- Yes --> C[Execute Loop Body] C --> B B -- No --> D[End]
1count = 0
2while count < 5:
3 print(count)
4 count += 1
3. break
and continue
Statements: Modifying Loop Behavior
-
break
: Exits the loop prematurely. -
continue
: Skips the current iteration and jumps to the next.
Notes:
if-elif-else
lets you make decisions, while for
and while
loops automate repetitive tasks.