Overview
Iteration—repeating a set of instructions—is fundamental in programming. In Python, a for loop runs a block of code a specific number of times, usually via range() which generates the sequence of integers for your loop variable.
Simple for loops (single value)
A basic for loop repeats the indented code a fixed number of times:
for i in range(5):
print("This is a loop!")
Counting with the loop variable
range(5) starts at 0 and ends at 4:
for i in range(5):
print("Loop number", i)
Start counting at 1 by specifying the start value:
for i in range(1, 6):
print("Loop number", i)
Using a step value
Control the increment (or decrement) with the third value in range():
# Even numbers from 2 to 10
for i in range(2, 11, 2):
print(i)
Count backwards with a negative step:
for i in range(10, 0, -1):
print(i)
User-defined loops
Let the user decide how many times to loop and what to print:
loopnum = int(input("Times to repeat: "))
word = input("Word to repeat: ")
for i in range(loopnum):
print(word)
Practice tasks
Task 1 – Repeat your name
Create a loop that prints your name 20 times.
Task 2 – Are we there yet?
Print “Are we there yet?” 150 times.
Task 3 – 100 to 150
Print every number from 100 to 150 (inclusive):
for i in range(100, 151):
print(i)
Task 4 – Even numbers 10 to 30
Use an appropriate step to print even numbers from 10 to 30:
for i in range(10, 31, 2):
print(i)
Task 5 – Countdown
Use a negative step to print a countdown from 10 to 1:
for i in range(10, 0, -1):
print(i)
Task 6 – Many Happy Birthdays
Ask the user for their age and then print “Happy Birthday!” that many times.
Task 7 – House number and name
Ask for a house number and a name, then print the name as many times as the number.