Back to: Python Programming
While loops continue to run until some requirement is met, for loops run a block of code a specific number of times. Each time the block runs is called an iteration and it can run over a range, string, sequence, anything that can be iterated.
Iterating over a range
In the code below:
# the variable "counter" increases by 1 with each iteration
# the iterations start at the first number in the range
# the iteration cease prior to the last number in the range
for counter in range(0, 11): # <-- (0 included, 11 excluded)
print(counter) # <-- This block is executed 10 times
The code below does the same thing, we assume a starting point of 0 – so 11 iterations
for counter in range(11):
print(counter) # <-- This block is executed 10 times
We can loop forwards or backwards:
for counter in reversed(range(1,11)):
print(counter)
print("!!~~BLAST OFF~~!!")
The for loop by range uses (first, last, step) – first is inclusive, last is exclusive and step determines how much to increment the counter variable by on each iteration.
for counter in (range(0, 21, 2)):
print(counter)
Outputs:
0
2
4
6
8
10
12
14
16
18
20
Iterating over a string
greeting = "GIDDAY MATE!"
for counter in greeting:
print(counter)
Commands continue or break
We want to list all of the numbers between 1 and 20 but we must exclude 13 The continue command allows the loop to continue iterating.
for counter in range(1, 21):
if counter == 13:
continue
else:
print(counter)
The break commend ends the look and breaks out of it
for counter in range(1, 21):
if counter == 13:
break
else:
print(counter)
More Examples:
# Iterating over a list
fruits = ['apple', 'banana', 'cherry']
for fruit in fruits:
print(fruit)
# Iterating over a string
word = 'Python'
for letter in word:
print(letter)
# Iterating over a range
for number in range(1, 5):
print(number)
Exercise:
Create a program that uses a “for” loop to iterate through a list of numbers and print each number multiplied by 2.
Python For Loops – Programming for Beginners – (5m:18s)