Control flow structures are essential in Python programming as they allow your code to make decisions, repeat tasks, and control the order of execution.
We’ll cover three fundamental structures:
Conditional Statements: Making decisions based on conditions.
Loops: Repeating a block of code multiple times.
Exceptions: Handling errors gracefully.
13.1 Conditional Statements
Conditional statements help execute certain code only if specific conditions are met.
13.1.1 Basic If-Else Statement
# Determine if a number is positive, negative, or zeronumber =-3if number >0:print(f"{number} is a positive number.")elif number <0:print(f"{number} is a negative number.")else:print(f"{number} is zero.")
-3 is a negative number.
Explanation:
if checks if number is greater than 0 and prints that it’s positive.
elif (else if) checks if number is less than 0 and prints that it’s negative.
else captures any other condition (zero here) and prints accordingly.
13.1.2 Nested Conditionals
# Classify an age into different life stagesage =25if age <13:print("Child")elif age <18:print("Teenager")else:if age <65:print("Adult")else:print("Senior")
Adult
Explanation:
The outer if-elif-else checks if age is less than 13 or 18, printing “Child” or “Teenager.”
If not, a nested if-else further checks if age is less than 65 or greater, printing “Adult” or “Senior.”
13.2 Loops
Loops repeat a block of code several times.
13.2.1 For Loops
For loops iterate over a range or collection.
Looping Over a Range
# Print numbers from 1 to 5for num inrange(1, 6):print(f"Number: {num}")
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Explanation:
range(1, 6) generates numbers from 1 to 5 (6 is exclusive).
Each number is printed using an f-string.
Looping Over a List
# List of colorscolors = ["red", "green", "blue"]# Loop through each color and print itfor color in colors:print(f"Color: {color}")
Color: red
Color: green
Color: blue
Explanation:
The list colors contains three strings.
for color in colors iterates over each item in the list, and each value is printed.
13.2.2 While Loops
A while loop continues to execute as long as a condition is True.
Example: Simple While Loop
# Countdown from 5 to 1count =5while count >0:print(f"Countdown: {count}") count -=1# Decrease count by 1
Initial Variable Setup: The variable count is initialized to 5.
While Loop Condition: The while loop runs as long as the condition count > 0 remains True. This condition is checked before each iteration starts.
Inside the Loop:
The print function outputs the current value of count, prefixed with “Countdown:”, using an f-string.
The statement count -= 1 decreases the value of count by 1. This shorthand notation is equivalent to count = count - 1.
After each decrement, count gets closer to 0.
Loop Exit:
Once count is no longer greater than 0 (meaning count is 0 or less), the while condition becomes False and the loop exits.
The decrement operation (count -= 1) ensures the loop will not run indefinitely and helps create a countdown sequence.
13.3 Exceptions
Exceptions handle errors that occur during execution without crashing the program.
Example: Handling Division by Zero
# Attempt division by zero and handle the errornumerator =10denominator =0try: result = numerator / denominatorprint(f"Result: {result}")exceptZeroDivisionError:print("Error: Cannot divide by zero.")
Error: Cannot divide by zero.
Explanation:
The try block contains code that might raise an error (division by zero here).
except ZeroDivisionError catches this specific error and prints an appropriate message.