Control Flow
## Learning Objectives
- Master if, elif, else statements
- Understand for and while loops
- Learn break, continue, pass
- Work with range() and enumerate()
## if Statement
### Basic if
```python
age = 18
if age >= 18:
print("Adult")
```
### if-else
```python
age = 15
if age >= 18:
print("Adult")
else:
print("Minor")
```
### if-elif-else
```python
score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"
print(f"Grade: {grade}") # B
```
### Ternary Expression
```python
age = 20
status = "adult" if age >= 18 else "minor"
print(status) # adult
```
## Comparison Operators
### Chained Comparisons
```python
x = 5
if 1 < x < 10:
print("x is between 1 and 10")
```
## for Loop
### Basic for Loop
```python
for i in range(5):
print(i) # 0, 1, 2, 3, 4
```
### Iterating Over Sequences
```python
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
```
### Range
```python
# range(stop)
for i in range(5):
print(i) # 0 to 4
# range(start, stop)
for i in range(2, 6):
print(i) # 2 to 5
# range(start, stop, step)
for i in range(0, 10, 2):
print(i) # 0, 2, 4, 6, 8
# Reverse
for i in range(5, 0, -1):
print(i) # 5, 4, 3, 2, 1
```
### enumerate()
```python
fruits = ["apple", "banana", "cherry"]
for index, fruit in enumerate(fruits):
print(f"{index}: {fruit}")
# 0: apple
# 1: banana
# 2: cherry
# Start from 1
for index, fruit in enumerate(fruits, start=1):
print(f"{index}: {fruit}")
```
### zip()
```python
names = ["Alice", "Bob", "Charlie"]
ages = [25, 30, 35]
for name, age in zip(names, ages):
print(f"{name} is {age}")
# Alice is 25
# Bob is 30
# Charlie is 35
```
### Iterating Over Dictionaries
```python
person = {"name": "Alice", "age": 25, "city": "NYC"}
# Keys
for key in person:
print(key)
# Keys explicitly
for key in person.keys():
print(key)
# Values
for value in person.values():
print(value)
# Key-value pairs
for key, value in person.items():
print(f"{key}: {value}")
```
## while Loop
### Basic while
```python
count = 0
while count < 5:
print(count)
count += 1
```
### while-else
```python
count = 0
while count < 5:
print(count)
count += 1
else:
print("Loop completed normally")
# Output: 0, 1, 2, 3, 4, "Loop completed normally"
```
## Loop Control
### break
```python
for i in range(10):
if i == 5:
break
print(i) # 0, 1, 2, 3, 4
```
### continue
```python
for i in range(5):
if i == 2:
continue
print(i) # 0, 1, 3, 4 (skips 2)
```
### pass
```python
for i in range(5):
if i == 2:
pass # Do nothing, continue
else:
print(i)
```
## Nested Loops
```python
for i in range(3):
for j in range(3):
print(f"({i}, {j})", end=" ")
print()
# (0, 0) (0, 1) (0, 2)
# (1, 0) (1, 1) (1, 2)
# (2, 0) (2, 1) (2, 2)
```
## List Comprehensions
### Basic
```python
squares = [x ** 2 for x in range(5)]
print(squares) # [0, 1, 4, 9, 16]
```
### With Condition
```python
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
# Also works:
# odds = [x for x in range(10) if x % 2 != 0]
```
### Nested
```python
matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for row in matrix for num in row]
print(flattened) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
```
## Dictionary Comprehensions
```python
squares = {x: x ** 2 for x in range(5)}
print(squares) # {0: 0, 1: 1, 2: 4, 3: 9, 4: 16}
names = ["Alice", "Bob", "Charlie"]
lengths = {name: len(name) for name in names}
print(lengths) # {'Alice': 5, 'Bob': 3, 'Charlie': 7}
```
## Set Comprehensions
```python
numbers = [1, 2, 2, 3, 3, 4, 5, 5]
unique_squares = {x ** 2 for x in numbers}
print(unique_squares) # {1, 4, 9, 16, 25}
```
## Generator Expressions
```python
# Like list comprehension but lazy
squares_gen = (x ** 2 for x in range(5))
print(squares_gen) #
for sq in squares_gen:
print(sq)
```
## Common Patterns
### Find in List
```python
numbers = [1, 5, 3, 8, 2]
target = 8
if target in numbers:
print(f"Found {target}")
else:
print(f"{target} not found")
```
### Find Index
```python
numbers = [1, 5, 3, 8, 2]
target = 8
for i, num in enumerate(numbers):
if num == target:
print(f"Found at index {i}")
break
else:
print("Not found")
```
### Sum and Count
```python
numbers = [1, 2, 3, 4, 5]
total = sum(numbers)
count = len(numbers)
average = total / count
print(f"Sum: {total}, Count: {count}, Average: {average}")
```
## Summary
- if/elif/else for conditional logic
- for loops iterate over sequences
- while loops repeat while condition is true
- range() generates number sequences
- enumerate() gives index and value
- zip() iterates multiple sequences
- break exits the loop, continue skips to next iteration
- List comprehensions: `[expr for item in iterable if condition]`
- Use indentation to define blocks
Comments
Comments powered by Giscus
To enable comments, add your Giscus embed code here.
Learn more about Giscus →