Control flow in Python determines the order in which statements are executed. It includes conditional statements, loops, and exception handling, which allow developers to create dynamic and logical programs.
1. Conditional Statements
Conditional statements in Python allow code execution based on certain conditions. The main control flow statements are if
, elif
, and else
.
if Statement
The if
statement executes a block of code only if a specified condition is True
.
x = 10 if x > 5: print("x is greater than 5")
if-else Statement
If the condition in the if
statement is False
, the else
block executes.
x = 3 if x > 5: print("x is greater than 5") else: print("x is 5 or less")
if-elif-else Statement
The elif
(short for “else if”) statement checks multiple conditions sequentially.
x = 7 if x > 10: print("x is greater than 10") elif x > 5: print("x is between 6 and 10") else: print("x is 5 or less")
2. Loops in Python
Loops allow repeated execution of a block of code. Python provides two types of loops: for
and while
.
for Loop
The for
loop iterates over a sequence such as a list, tuple, or string.
fruits = ["Apple", "Banana", "Cherry"] for fruit in fruits: print(fruit)
Using range()
to iterate over numbers:
for i in range(5): print(i) # Prints numbers 0 to 4
while Loop
The while
loop executes as long as a condition remains True
.
x = 0 while x < 5: print(x) x += 1
3. Loop Control Statements
Python provides special statements to control the behavior of loops.
break Statement
The break
statement stops a loop before it completes all iterations.
for i in range(10): if i == 5: break # Exits the loop when i is 5 print(i)
continue Statement
The continue
statement skips the current iteration and proceeds to the next one.
for i in range(5): if i == 2: continue # Skips when i is 2 print(i)
pass Statement
The pass
statement is a placeholder that does nothing. It is used when a statement is required syntactically but no action is needed.
for i in range(3): pass # Placeholder for future code
4. Exception Handling
Exception handling in Python helps in managing runtime errors using try
, except
, finally
, and raise
.
try-except Block
Handles errors gracefully without crashing the program.
try: x = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero")
finally Block
The finally
block executes regardless of whether an exception occurs.
try: print(5 / 0) except ZeroDivisionError: print("Error: Division by zero") finally: print("This always executes")
raise Statement
The raise
statement manually triggers an exception.
x = -1 if x < 0: raise ValueError("Negative values are not allowed")
Control flow structures are essential for writing logical and efficient Python programs. Mastering conditional statements, loops, and exception handling will help you build robust applications.