Control Flow
Master conditional statements, loops, and list comprehensions to control the execution flow of your Python programs.
Conditional Statements
Python uses if, elif, and else keywords for conditional branching. Unlike many languages, Python relies on indentation rather than curly braces to define code blocks. The elif keyword is short for else if and allows you to chain multiple conditions together. Python also supports ternary expressions for concise conditional assignments in a single line.
# Basic if/elif/else
temperature = 28
if temperature > 30:
print("It's hot outside")
elif temperature > 20:
print("It's a nice day")
elif temperature > 10:
print("It's a bit chilly")
else:
print("It's cold outside")
# Ternary expression
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # "adult"
# Chained comparisons
x = 15
if 10 < x < 20:
print("x is between 10 and 20")
For Loops and Range
The for loop in Python iterates over any iterable object such as lists, strings, tuples, and ranges. The range() function generates a sequence of numbers and is commonly used for counting iterations. Python's for loop is more like a foreach in other languages, directly providing each element rather than an index. The enumerate() function is useful when you need both the index and the value.
# Iterating over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Using range
for i in range(5):
print(i) # 0, 1, 2, 3, 4
for i in range(2, 10, 3):
print(i) # 2, 5, 8
# Enumerate for index and value
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# Iterating over a string
for char in "Python":
print(char, end=" ") # P y t h o n
While Loops
While loops repeat a block of code as long as a condition remains true. They are useful when you do not know in advance how many iterations are needed. Be careful to ensure the loop condition eventually becomes false to avoid infinite loops. Python provides break to exit a loop early and continue to skip to the next iteration.
# Basic while loop
count = 0
while count < 5:
print(count)
count += 1
# While with break and continue
numbers = [1, 3, 5, 8, 10, 12, 15]
for num in numbers:
if num % 2 == 0:
print(f"First even number: {num}")
break
print(f"{num} is odd, skipping")
# While with else (runs if loop completes without break)
n = 7
i = 2
while i < n:
if n % i == 0:
print(f"{n} is not prime")
break
i += 1
else:
print(f"{n} is prime")
List Comprehensions
List comprehensions provide a concise way to create lists based on existing iterables. They combine a for loop and an optional condition into a single readable expression. List comprehensions are not only more Pythonic but also generally faster than equivalent for loops. You can also create dictionary comprehensions, set comprehensions, and generator expressions using similar syntax.
# Basic list comprehension
squares = [x ** 2 for x in range(10)]
print(squares) # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
# With condition
evens = [x for x in range(20) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8, 10, 12, 14, 16, 18]
# Nested comprehension
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(matrix) # [[1, 2, 3], [2, 4, 6], [3, 6, 9]]
# Dictionary comprehension
word = "hello"
char_count = {ch: word.count(ch) for ch in set(word)}
print(char_count) # {'h': 1, 'e': 1, 'l': 2, 'o': 1}
# Set comprehension
unique_lengths = {len(w) for w in ["hi", "hello", "hey", "ok"]}
print(unique_lengths) # {2, 3, 5}