Control Structures in Python
Control Structures in Python
Control structures are blocks of programming that analyze variables and choose directions in which
to go based on given parameters.
They allow for conditional execution, repeated execution, or more complex flow control.
1. Conditional Statements
Python provides several types of conditional statements:
a. if statement
b. if-else statement
c. if-elif-else statement
Example:
if x > 0:
print("Positive number")
elif x == 0:
print("Zero")
else:
print("Negative number")
2. Loops
Python supports two types of loops:
a. for loop: Used for iterating over a sequence (like a list, tuple, or string).
Example:
for i in range(5):
print(i)
b. while loop: Repeats as long as a condition is True.
Example:
while x < 10:
print(x)
x += 1
3. Control Flow Statements
These statements are used to modify the flow of execution within loops:
a. break: Exits the loop.
b. continue: Skips to the next iteration.
c. pass: Does nothing, acts as a placeholder.
Example:
for i in range(5):
if i == 3:
break # Exit loop when i is 3
print(i)
4. Exception Handling
Python uses try-except blocks to handle exceptions and ensure the program continues running.
Example:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
5. Function Control
Python functions can use control structures to manage execution flow within them.
Example:
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n - 1)