Chapter 6, Lesson 3 Text
Chapter Six: Lists and Loops
Lesson Three: "For" Loops
Now that you understand how to create large data sets with lists and tuples, how might you write code to do something useful with each item in the list? A list with 5 items could be accessed with 5 statements using , , ,  and  index values. However, imagine the code you would need to write for a much larger list!
Fortunately, Python allows you to create program loops that execute the same set of statements repeatedly. You can apply loops to list processing by running the same set of statements against each value or element in a list. Walking through each item in a list or collection is called iteration. In this lesson, you are going to learn how to write a variety of "for" loops to iterate through a set of values and do useful work with each value.
"for" Loops to Iterate over Lists and Tuples
In Python, you can write a "for" loop to iterate through each value in a list or tuple. You begin the loop with the "for" keyword, and then declare a new variable name that will only be valid for the statements within the loop. Next comes the "in" keyword, followed by the list or tuple that contains your data. Finally, add a colon (:) at the end of the statement.
for item in listName: # run this code repeatedly using the "item" name to access each list value
The item name can be any valid variable name that you like. This variable will be automatically updated each time through the loop, containing one list value at a time. The listName, similarly, is any variable that contains a list or tuple.
After the "for" statement line, you will add one or more statements that should be run inside the loop. Remember to indent all those statements an equal amount to the right to show they belong to the "for" loop. After the "for" loop has iterated over each item, the loop ends and the program will continue at the first un-indented line of code after the loop body. The statements indented inside the loop are often called the loop "body".
Let's check out a concrete example. The code below will iterate over all the elements in the favoriteSports tuple and print each to the screen. Try it and see!
Try It Now
It's important to understand that the item variable within the "for" loop contains a copy of the value within the actual list element. You can freely change the item variable contents within the loop, but those changes are not saved back to the original list.
The example below demonstrates this point. Inside the "for" loop, we update the sport item variable to a new value. After the loop finishes, we print the original list to show those changes had no effect on the list data.
Try It Now
"for" Loops to Iterate over Strings
Lists and tuples are not the only thing you can iterate over with a "for" loop! Strings are basically just a collection of individual letters, and you can use a "for" loop to walk through a string, one character at a time.
The following code asks the user to enter a word. It then loops over each character in that word, counting the number of "e" characters found. After the loop ends, the final count is printed. Run the code yourself to see how it works.
Try It Now
"for" Loops to Iterate over a Range
Programmers in other languages will frequently use "for" loops to iterate a specific number of times. Python supports this as well using ranges. Let's say you want a numeric index variable to start at 1 and iterate up to 4 (1, 2, 3, 4). You could define this range using "range(1,5)" after the "in" keyword. The first number in a range is the starting point, and the last number is one more than the ending value.
for index in range(1,5): # index will become 1, 2, 3, 4 inside the loop
The numeric index variable can be used for any kind of calculation or task that your program demands. For example, let's say your program needed to add up all the numbers between 1 and 100. We could write a "for" loop with a range to get each of those numbers and add them to a running total.
The variable name "i" is often used in loops when iterating over a numeric sequence. "i" doesn't follow the normal best practice rules for making descriptive variable names. However, "i" is well-understood by programmers to represent a numeric index variable in a loop.
Try It Now
Try changing the range in the example above and running the code to confirm the results. Can you add up the numbers between 2 and 6 or between 1 and 10? You might want to add a print() statement inside the loop to show you the value of the index variable on each pass through the loop.
You don't need to hard-code the starting or ending range number! You can use variables or any expression that evaluates to an integer, as demonstrated below.
lower = 5 upper = 100 for i in range (lower, upper): # loop from 5 up through 99 print(i) for i in range(1,upper + 1): # loop from 1 up through 100 print(i)
Work with Me: Calculating a Factorial
In mathematics, the factorial of a number is calculated by multiplying together all the numbers from 1 up to and including the target number. Factorials are written with an exclamation point after the number, as in "5!". Some example factorials are shown below. Note that the factorial of 0 is always 1.0! = 1 1! = 1 2! = 1 * 2 = 2 3! = 1 * 2 * 3 = 6 4! = 1 * 2 * 3 * 4 = 24 5! = 1 * 2 * 3 * 4 * 5 = 120
In this exercise, you are going to ask the user for an input number. Then, create a "for" loop that iterates from 1 up through the target number, keeping a running total of the multiplication results. Finally, at the end of the loop, print out the total results.
The code below gives you a few lines and comments to get started. Create the "for" loop and factorial calculation on your own!
Try It Now
Test your code using inputs like 4 or 5 that you can easily verify.Enter a positive integer: 5 Factorial = 120
"break" Statement inside a "for" Loop
There may be times when you want to exit a "for" loop before it has finished processing every value in the list or range. To do this, you can add a statement containing the "break" keyword. "break" tells Python to immediately exit the loop and continue the program normally after the loop body.
Let's imagine that you want to write a program that scans a string and prints numeric index that corresponds to the first "e" character. You can visualize a string as a list of characters, and each character is identified by a number starting at 0 and going up by 1 each character to the right. The 7-character string "Banzai!", as shown below, would have character index values from 0 to 6, where the first "B" is index 0 and the last character is index 6.
We can find character index values using a "for" loop that examines each letter, keeping an increasing count of that letter's numeric index. If the letter matches the one we're looking for, the program can print out the current character index and then "break" out of the loop. There is no reason to look at the rest of the letters after we find our target letter.
Study the code below to make sure you understand how it works. Try running it a few times with different input words like "hello" and "cheese". Do you get the expected output in each case?
Try It Now
"continue" Statement inside a "for" Loop
Your program may want to skip the remainder of a "for" loop body in the current iteration, but continue iterating over the remaining values. You can use the "continue" keyword to do just that! When Python sees a "continue" statement, it will halt the current loop iteration and start at the top of the loop with the next value.
In the following example, we iterate over a range of values from 1 to 10. We check each value to see if it is even, and if so, we continue to the next value. We only reach the print() statement in the "for" loop body if the value is odd.
Try It Now
Remember, the modulus operator (%) will divide the left number by the right number and give you the remainder. If you divide an even number by 2, the remainder should be zero. So, the logical expression (i % 2 == 0) is dividing the loop index value by 2 and returning True if the remainder is 0 (meaning, the loop index value is an even number).
"else" Statement after a "for" Loop
As you have seen, "for" loops are very flexible with many options. One last thing you might want to add to a "for" loop is an "else" statement. The "else" statement marks a body of code that will run after the loop has completely finished. This could be useful if there is some message or some special processing that you want to do when the loop is done.
In the example below, we print out the contents of a list using a "for" loop. An "else" block contains a final print() statement to confirm that we have finished the list.
Try It Now
Of course, all non-indented statements you place after the loop body will run when the loop is complete. So, what is special about marking a block of code with the "else" statement? The "else" statement will actually be skipped if your loop exits early due to a break. So, you would want to use "else" to mark some final logic to run only if the loop completes normally.
In the example below, we set up a list of pets. We then ask the user to try and guess one of the pets in the list. We use a "for" loop to examine each pet in the list and compare it to the user's guess. If there is a match, we print out a successful message and break out of the loop. If the loop runs to completion without any match, then the "else" logic will kick in and print out a different message.
Try It Now
Work with Me: What's in Your Pocket?
In this exercise, you are going to write a program that prompts the user to enter up to 3 items that are in his or her pocket, and then print that list back to the screen. If the user has less than 3 items, they will break free of the loop early, otherwise you will also print a "Your pockets are full" message.
When the user is prompted for a value with input(), simply hitting "Enter" without entering any data will result in an empty string ("") being returned from the input() function. This empty result will be the user's signal that no more items remain in the pocket, so the loop should end early at that point.
Follow the steps below to complete the entire program.
- Initialize an empty list called items (this is done for you below).
- Create a "for" loop that will run 3 times (e.g. use a range(1,4)). Within the loop:
- Ask the user "What's in your pocket?" using input() and store the result in a variable named item.
- If the item is not empty (if item != "")
- Call items.append(item) to add the item to the items list
- Use a break statement to exit the "for" loop right away
- Add an "else" section after the "for" loop that will run when loop completes without breaking early.
- Within the "else" section, print the message "Your pockets are full".
- Finally, print the entire list of items that the user entered (this is done for you below)
We have given you a few lines and comments to get started. Complete the rest on your own!
Try It Now
Test your code using both a full 3-item list and a list that only has one or two items. You should see results like the examples below.What's in your pocket? keys
What's in your pocket? coins
What's in your pocket? lint
Your pockets are full
Your pockets contain: ['keys', 'coins', 'lint']What's in your pocket? candy
What's in your pocket? wallet
What's in your pocket?
Your pockets contain: ['candy', 'wallet']
End of Lesson