Lesson 1 of 0
In Progress

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

models = [“jeep”, “tesla”, “audi”]
for i in models:
  print(i)
models = (“jeep”, “tesla”, “audi”)
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

models = [“jeep”, “tesla”, “audi”]
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

models = [“jeep”, “tesla”, “audi”]
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

for r in range(10):
  print(r)
models = [“jeep”, “tesla”, “audi”]
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).

for r in range(5, 10):
  print(r)

Nested Loops

Nested loops mean a loop statement inside another loop statement.

cars = [“car_1”, “car_2”, “car_3”]
models = [“jeep”, “tesla”, “audi”]

for c in cars:
  for m in models:
    print(c, m)