Control Structures in Python
Control structures in Python allow you to control the flow of your program. They include conditional statements (if-elif-else) and loops (for, while).
If-Elif-Else Statements
The if-elif-else
statement is used to execute a block of code based on multiple conditions.
age = 20
if age < 13:
print("You are a child.")
elif age < 18:
print("You are a teenager.")
else:
print("You are an adult.")
Loops
Loops are used to execute a block of code repeatedly. Python supports for
and while
loops.
# For Loop
for i in range(5):
print(i)
# While Loop
count = 0
while count < 5:
print(count)
count += 1
Nested Loops
You can nest loops inside other loops to handle complex logic.
for i in range(3):
for j in range(3):
print(f"({i}, {j})")
Break and Continue
The break
statement exits the loop, while the continue
statement skips the current iteration.
# Break Example
for i in range(10):
if i == 5:
break
print(i)
# Continue Example
for i in range(10):
if i % 2 == 0:
continue
print(i)
List Comprehensions
List comprehensions provide a concise way to create lists.
# Create a list of squares
squares = [x**2 for x in range(10)]
print(squares)
Error Handling: Try-Except
The try-except
block is used to handle errors gracefully.
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero.")
finally:
print("Execution completed.")
Next: Functions