Loops
Repeating operations with for and while, and controlling them with break and continue.
The for loop
for epoch in range(1, 4):
print("Training epoch", epoch)range(start, stop, step) generates numbers from start up to, but not including, stop.
Going over the elements of a list:
models = ["SVM", "Random Forest", "CNN"]
for m in models:
print(m)enumerate and zip
for i, m in enumerate(models):
print(i, m) # the index and the element
names = ["A", "B"]
scores = [0.8, 0.9]
for n, s in zip(names, scores):
print(n, s)The while loop
loss = 1.0
while loss > 0.1:
loss *= 0.5
print(loss) # 0.0625Make sure the condition will become false at some point, or you will get an infinite loop.
break and continue
for x in [3, -1, 4, 0, 5]:
if x < 0:
continue # skip negative values
if x == 0:
break # stop at zero
print(x) # prints 3, then 4List comprehensions
A short syntax for building a list from a loop:
squares = [x ** 2 for x in range(5)] # [0, 1, 4, 9, 16]
evens = [x for x in range(10) if x % 2 == 0]In large-scale data analysis we avoid explicit loops as much as possible and use vectorized operations in NumPy and pandas, as we will see later.
Lesson terms
- Infinite loop
- A while loop whose condition never becomes false, so it continues without stopping.
- Iterable
- An object whose elements can be gone through one after another, such as lists, strings, dictionaries and range.
Abstract
A for loop goes over the elements of an iterable object such as a list or a range, and a while loop repeats as long as the condition is true. break ends the loop and continue skips the current iteration, and enumerate and zip help to go over indices or over several sequences together.
Review questions
-
What values does range(2, 8, 2) generate?
2, 4 and 6, because the end 8 is not included.
-
What is the difference between break and continue?
break ends the whole loop, and continue skips the rest of the current iteration and moves to the next one.
Sources and references
Complete the lesson
You have completed all the lessons in the track! You can now request the track completion certificate.
Request the certificate