Control_Structures_in_Python
Control_Structures_in_Python
Control structures are blocks of programming that analyze variables and choose directions in which
They allow for conditional execution, repeated execution, or more complex flow control.
1. 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
a. for loop: Used for iterating over a sequence (like a list, tuple, or string).
Example:
for i in range(5):
print(i)
Example:
print(x)
x += 1
These statements are used to modify the flow of execution within loops:
Example:
for i in range(5):
if i == 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:
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)