Control Flow
Control flow refers to the order in which the program's code executes. Python provides several control flow statements that allow you to control the flow of your program based on conditions, repeat code blocks, and more.
Conditional Statements
Conditional statements allow you to execute different code blocks based on whether a condition is true or false.
if Statement
The if
statement executes a block of code if a specified condition is true:
x = 10
if x > 0:
print("x is positive")
if-else Statement
The if-else
statement executes one block of code if a condition is true and another block if it's false:
x = -5
if x > 0:
print("x is positive")
else:
print("x is not positive")
if-elif-else Statement
The if-elif-else
statement allows you to check multiple conditions:
x = 0
if x > 0:
print("x is positive")
elif x < 0:
print("x is negative")
else:
print("x is zero")
Nested if Statements
You can nest if statements inside other if statements:
x = 10
y = 5
if x > 0:
print("x is positive")
if y > 0:
print("y is also positive")
else:
print("y is not positive")
Conditional Expressions (Ternary Operator)
Python provides a concise way to write simple if-else statements:
x = 10
result = "positive" if x > 0 else "non-positive"
print(result) # Outputs: "positive"
Loops
Loops allow you to execute a block of code multiple times.
for Loop
The for
loop is used to iterate over a sequence (like a list, tuple, string, etc.) or other iterable objects:
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Iterating over a string
for char in "Python":
print(char)
# Iterating over a range
for i in range(5): # 0, 1, 2, 3, 4
print(i)
while Loop
The while
loop executes a block of code as long as a condition is true:
count = 0
while count < 5:
print(count)
count += 1
break Statement
The break
statement is used to exit a loop prematurely:
for i in range(10):
if i == 5:
break
print(i) # Outputs: 0, 1, 2, 3, 4
continue Statement
The continue
statement is used to skip the current iteration and continue with the next one:
for i in range(10):
if i % 2 == 0: # Skip even numbers
continue
print(i) # Outputs: 1, 3, 5, 7, 9
else Clause in Loops
Both for
and while
loops can have an optional else
clause that executes when the loop completes normally (i.e., not terminated by a break
statement):
# With for loop
for i in range(5):
print(i)
else:
print("Loop completed")
# With while loop
count = 0
while count < 5:
print(count)
count += 1
else:
print("Loop completed")
# With break
for i in range(5):
if i == 3:
break
print(i)
else:
print("This won't execute because the loop was exited with break")
Loop Control Techniques
range() Function
The range()
function generates a sequence of numbers:
# range(stop)
for i in range(5): # 0, 1, 2, 3, 4
print(i)
# range(start, stop)
for i in range(2, 6): # 2, 3, 4, 5
print(i)
# range(start, stop, step)
for i in range(1, 10, 2): # 1, 3, 5, 7, 9
print(i)
enumerate() Function
The enumerate()
function adds a counter to an iterable:
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Outputs:
# 0: apple
# 1: banana
# 2: cherry
zip() Function
The zip()
function combines elements from multiple iterables:
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age} years old")
# Outputs:
# Alice is 25 years old
# Bob is 30 years old
# Charlie is 35 years old
Comprehensions
Comprehensions provide a concise way to create lists, dictionaries, and sets based on existing iterables.
List Comprehension
# Create a list of squares
squares = [x**2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With a condition
even_squares = [x**2 for x in range(10) if x % 2 == 0]
print(even_squares) # [0, 4, 16, 36, 64]
Dictionary Comprehension
# Create a dictionary of squares
square_dict = {x: x**2 for x in range(5)}
print(square_dict) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
# With a condition
even_square_dict = {x: x**2 for x in range(10) if x % 2 == 0}
print(even_square_dict) # {0: 0, 2: 4, 4: 16, 6: 36, 8: 64}
Set Comprehension
# Create a set of squares
square_set = {x**2 for x in range(5)}
print(square_set) # {0, 1, 4, 9, 16}
# With a condition
even_square_set = {x**2 for x in range(10) if x % 2 == 0}
print(even_square_set) # {0, 4, 16, 36, 64}
Advanced Control Flow
try-except Statement
The try-except
statement is used for exception handling:
try:
result = 10 / 0
except ZeroDivisionError:
print("Cannot divide by zero")
# With multiple except blocks
try:
value = int("abc")
except ValueError:
print("Invalid conversion")
except ZeroDivisionError:
print("Cannot divide by zero")
# With else and finally
try:
result = 10 / 2
except ZeroDivisionError:
print("Cannot divide by zero")
else:
print("Division successful:", result)
finally:
print("This always executes")
with Statement
The with
statement is used for resource management:
# File handling with 'with'
with open("example.txt", "w") as file:
file.write("Hello, World!")
# File is automatically closed after the block
assert Statement
The assert
statement is used for debugging:
def calculate_average(numbers):
assert len(numbers) > 0, "List cannot be empty"
return sum(numbers) / len(numbers)
# This will raise an AssertionError
# calculate_average([])
Try experimenting with control flow statements in the code playground below!
Code Playground
Code output will appear here...