Python looping (for + while)

making events happen again and again in Python
2025-11-04 14:17
// updated 2025-11-05 17:18

Loops allow us to perform the same functions (or let the same events) happen over and over again.

In programming, we have two main types of loops:

  • for loops - do something for a specific number of times
  • while loops - do something until something else happens

Why loops?

We use loops because we want to use just one line to do some repetitive action, e.g. printing out numbers from 1 to 5; we could do this:

print(1)
print(2)
print(3)
print(4)
print(5)

But what if we want to do that from 1 to 100? It would be far too repetitive to type print and the number 100 times! There exists a fundamental concept called "DRY" in programming:

"Don't repeat yourself!"

If we find ourselves writing something more than once in a row, then we have likely repeated ourselves; we should instead strive to write an instruction in as few lines as possible!

Thus, the general idea of a loop is:

  • do something, for a certain amount of time (or for as long as something happens)

for loop

We use this kind of loop when we know how many times we want to run the loop:

# this outputs the numbers from 1 to 5 each on its own line

for counter in range(1, 6):
  print(counter)

# this outputs the numbers from 1 to my_limit each on its own line

my_limit = 10

for counter in range(1, my_limit+1):
  print(counter)

# this outputs the numbers from lower to upper each on its own line

lower = 5
upper = 10

for counter in range(lower, upper+1):
  print(counter)

As we can see in the examples above, the for keyword accompanies the keywords in and range!

for loop with lists

The loop has a simpler variant (without a call to range) when it comes to the list (a data structure similar to an array, that we will cover later):

names = [ "A", "B", "C", "E", "G" ]

for name in names:
  print(name)

# Output:
# A 
# B 
# C 
# E
# G

Nested for loops

We can have loops inside of loops, i.e. a flow that looks at lists and then lists inside of lists:

teams = [['Joe', 'Al', 'Bo'], ['Dan', 'Jon', 'Mo']]

for team in teams: 
  for player in team:
    print(player)

# Output:
# Joe
# Al 
# Bo 
# Dan 
# Jon 
# Mo

while loop

We use the while loop if we want to stop a loop when a certain condition is no longer true:

i = 0

while (i < 3):
  i += 1
  print(i)  

# Output:
# 1
# 2
# 3

Note that when the code evaluates the while statement, its indented code block still executes (so 3 still prints even though the counter variable is no longer less than 3!)

⬅️ older (in textbook-python)
🐍 Python match + case
newer (in textbook-python) ➡️
Python functions 🐍
⬅️ older (in code)
🐍 Python match + case
newer (in code) ➡️
Python functions 🐍
⬅️ older (posts)
🐍 Python match + case
newer (posts) ➡️
Python functions 🐍