Loops

Unobi Training - Level 1

Overview

Loops allow you to repeat actions in Python without writing the same code over and over.

In this lesson we cover:

Why Loops Matter

print("Processing order 1")
print("Processing order 2")
print("Processing order 3")
        

Loops help us avoid repeating code like this and make programs more efficient.

For Loops

for i in range(5):
    print(i)
        

A for loop repeats a block of code a specific number of times.

Using range()

for order in range(1, 6):
    print("Processing order", order)
        

range() controls how many times the loop runs.

Iteration

for i in range(3):
    print("Iteration:", i)
        

Each time a loop runs is called an iteration.

While Loops

count = 0

while count < 5:
    print("Count is", count)
    count += 1
        

A while loop runs while a condition is true.

Infinite Loops

# while True:
#     print("This runs forever")
        

Infinite loops never stop unless manually interrupted.

break

for order in range(1, 6):
    if order == 4:
        break
    print(order)
        

break stops a loop early.

continue

for order in range(1, 6):
    if order == 3:
        continue
    print(order)
        

continue skips one iteration.

Practice

Download the interactive notebook:
Download loops.ipynb