The for Loop
A counted loop iterates an exact number of times. In Python, we use the for statement to write a counted loop. The for statement is designed to work with a sequence of data items called a list. Here is the general format:
The for statement works like this: the variable is assigned the first value in the list (a comma-separated sequence of data items that are enclosed in a set of square brackets is called a list in Python). The statements in the body of the loop are then executed. Next, the variable is assigned the next value in the list, and the statements in the body of the loop are executed again. This continues until variable has been assigned the last value in the list.
Here is an example that counts from 1 to 10, this time with a for loop:
1 2 |
for number in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]: print(number) |
Note that the items in the list do not have to be consecutively ordered. For example, this for loop prints 5 odd numbers between 1 and 9 in the order they appear in the list.
1 2 |
for number in [3, 7, 1, 9, 5]: print(number) |
Also, the list of values may contain any Python data type: int, float, str, or bool.
1 2 |
for item in [3.14, "Vik-20", 7, True]: print(item) |
The range() Function
Obviously, the key to making a for loop do what you want is the list of values that it iterates over. What if you wanted a loop to iterate over the values 1 through 1000? Typing this list by hand would be painful and result in hard to read code… if only there was a better way…
There is! Python provides a built-in function named range() that we can use to generate a special kind of object called an iterable which provides a sequence of values. To view the sequence as a list in the Python shell, we can use a function called list() to help. For example:
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
In its simplest form, the range() function returns a sequence of integers from 0 up to, but not including, the argument value. Let’s use this in a for loop:
1 2 |
for number in range(10): print(number) |
This code will print the numbers from 0 to 9 (10 is not included in the list). But what if we want to start our list at a value other than 0? For example, let’s say we want to display the numbers from 1 to 10. To do this we use a different version of the range() function that takes two arguments. The first argument is the starting value of the list and the second argument is used as the ending limit.
1 2 |
for number in range(1, 11): print(number) |
This code will print the numbers from 1 to 10 (11 is not included in the list). By default, the range() function produces a list of numbers that increase by 1. If you pass a third argument to the range() function, that argument is used as a step value. Instead of increasing by 1, each number in the list will increase by the step value.
1 2 |
for number in range(1, 10, 2): print(number) |
This code will print the odd numbers between 1 and 9. When the step value is a positive integer, the range() function generates a list with numbers that increase from lowest to highest. Alternatively, you can pass a negative step value to generate a list of numbers from highest down to lowest like this:
1 2 |
for number in range(10, 0, -1): print(number) |
This code will print the numbers from 10 down to 1 (0 is not included).
The break Statement
In some situations, it can be useful to be able to terminate a loop early. To do this you simply put a break statement (usually within some sort of if statement) inside a while or for loop. Program execution continues with the first line of code following the loop structure.
Here’s our example that counts from 1 to 10 again, but this time the loop exits early when number is assigned the value 5.
1 2 3 4 5 6 7 |
for number in range(1, 11): if number == 5: print("I hate number 5, exiting the loop!") break print("I love number", number) print("All Done!") |
The continue Statement
Related to the break statement, the continue statement causes any remaining code in the loop to be skipped and the next iteration of the loop to start. Here’s a similar example counting from 1 to 10, but this time the loop skips to the next iteration when number is assigned the value 5.
1 2 3 4 5 6 7 |
for number in range(1, 11): if number == 5: print("I hate number 5, skipping this iteration!") continue print("I love number", number) print("All Done!") |
Although you can use break and continue in any loop you create, they should be used sparingly. Both break and continue make it harder for someone (including you!) to see the logical flow of a loop and understand under what condition(s) it ends.
You Try!
-
- Start a new page in your Learning Journal titled “2-4 Counted Loops“. Carefully read the notes above and in your own words summarize the key ideas from each section.
- Try to figure out what the following code will display, then check your hypothesis using the Python interpreter.
123456total = 0for count in range(1, 6):total += countprint(total) - Try to figure out what each of the following for loops will display, then check your hypothesis using the Python interpreter.
1234567891011for number in range(6):print(number)for number in range(2, 6):print(number)for number in range(0, 501, 100):print(number)for number in range(10, 5, -1):print(number)