Lesson #11: For Loops
A for loop is used for iterating over an iterable like string, tuple, and list. With the for loop, we can execute a set of statements, once for each item in a list, tuple, set etc.
Examples
for i in models:
print(i)
for i in models:
print(i)
The Break Statement
The break statement is used to bring the control out of the loop before it has looped through all the items.
Example
for i in models:
print(i)
if i == “tesla”:
break
The Continue Statement
The continue statement is used to bring the control out of the loop only for the current iteration.
Example
for i in models:
print(i)
if i == “tesla”:
continue
The Range() Function
The range()
function is a built-in function that is used when a user needs to perform an action a specific number of times.
Examples
print(r)
for r in range(len(models)):
print(models[r])
The Range(start, end) Function
The range()
function can be used with two arguments, the starting point, and the ending point. Users can use range() to generate a series of numbers from start to end using a range(start, end).
print(r)
Nested Loops
Nested loops mean a loop statement inside another loop statement.
models = [“jeep”, “tesla”, “audi”]
for c in cars:
for m in models:
print(c, m)