Python For Loop and the range() Function
The while loop keeps looping while its condition is True (which is the reason for its name), but what if you want to execute a block of code only a certain number of times? You can do this with a for loop statement and the range()
In code, a for statement looks something like for i in range(5): and always includes the following:
- The for keyword.
- A variable name.
- The in keyword
- A call to the range() method with up to three integers passed to it.
- A colon
- Starting on the next line, an indented block of code (called the for clause)
Let’s create a new program called fiveTimes.py to help you see a for loop in action.
print('My name is') for i in range(5): print('Jimmy Five Times (' + str(i) + ')')
The code in the for loop’s clause is run five times. The first time it is run, the variable i is set to 0. The print() call in the clause will print Jimmy Five Times (0). After Python finishes an iteration through all the code inside the for loop’s clause, the execution goes back to the top of the loop, and the for statement increments i by one. This is why range(5) results in five iterations through the clause, with i being set to 0, then 1, then 2, then 3, and then 4. The variable i will go up to, but will not include, the integer passed to range(). Figure shows a flowchart for the fiveTimes.py program.
When you run this program, it should print Jimmy Five Times followed by the value of i five times before leaving the for loop.
My name is Jimmy Five Times (0) Jimmy Five Times (1) Jimmy Five Times (2) Jimmy Five Times (3) Jimmy Five Times (4)
As another for loop example, consider this story about the mathematician Karl Friedrich Gauss. When Gauss was a boy, a teacher wanted to give the class some busywork. The teacher told them to add up all the numbers from 0 to 100. Young Gauss came up with a clever trick to figure out the answer in a few seconds, but you can write a Python
program with a for loop to do this calculation for you.
total = 0 for num in range(101): total = total + num print(total)
The result should be 5,050. When the program first starts, the total variable is set to 0. The for loop v then executes total = total + num 100 times. By the time the loop has finished all of its 100 iterations, every integer from 0 to 100 will have been added to total. At this point, total is printed to the screen. Even on the slowest computers, this program takes less than a second to complete.
(Young Gauss figured out that there were 50 pairs of numbers that added up to 100: 1 + 99, 2 + 98, 3 + 97, and so on, until 49 + 51. Since 50 × 100 is 5,000, when you add that middle 50, the sum of all the numbers from 0 to 100 is 5,050. Clever kid!).