Chapter 5 Control Flow
5.0.2 Looping Extra
for-else
In a for-else block, if break runs in the for loop, else doesn’t run if break doesn’t run in the for loop, else will run
breakvscontinue
break stops the entire loop immediately when L=‘C’, break happens, and the entire loop stops.
## A
## B
continue skips to the next iteration, without stopping the entire loop
## A
## B
## D
## E
when L='C', continue executes, and the iteration for L='C' is skipped.
Instead we skip over to the next iteration immediately, where L='D'
Note that continue doesn’t stop the entire loop like break
- enumerate & zip
enumerate() allows us to generate both index and element at the same time when iterating through a list (or similar iterable).
## 0 A
## 1 B
## 2 C
## 3 D
## 4 E
zip() allows us to iterate through 2 or more lists (or iterables) at once.
names = ['Adam', 'Eve', 'Joe']
ages = [25,35,18]
for name, age in zip(names, ages):
print(name, age)## Adam 25
## Eve 35
## Joe 18