With range a loop repeats a number of times. But often you want to go through a group of values you already have, like a week of temperatures. Write the values in square brackets [ ] after in:
for temp in [9, 7, 13, 11]:
print(temp)9 7 13 11
On each turn the variable temp takes the next value in order, from first to last. You can also store the values in a variable first and put its name after in:
past_temp_list = [9, 7, 13, 11, 10, 8, 14]
for temp in past_temp_list:
print(temp)9 7 13 11 10 8 14
| Code | The variable takes |
|---|---|
| for i in range(3): | 0, 1, 2 |
| for temp in [9, 7, 13]: | 9, 7, 13 |
| for letter in "abc": | a, b, c |
Inside the loop you can do anything with the value, for example add it up. Start the total at zero before the loop and print it after it:
prices = [15, 20, 10]
total = 0
for price in prices:
total = total + price
print("Total: " + str(total))Total: 45
Going through the letters of a text
A text is a row of characters, so if you put it after in you get its letters one at a time:
for letter in "Python":
print(letter)P y t h o n
With an if inside the loop you can count a certain letter:
word = "banana"
count = 0
for letter in word:
if letter == "a":
count = count + 1
print(count)3
for x in "prices": goes through the letters of the word prices, not the values stored in the variable.Practice
Print every value of num_list with a for loop, and name the loop variable num.
num_list = [4, 8, 12, 16]
Press Run to see the result. Store Good morning, Good night and Hello (in that order) in word_list, then print them with a for loop whose variable is word.
Press Run to see the result. Fill in the two blanks so the seven temperatures are printed one per line.
past_temp_list = [7, 10, 12, 9, 11, 8, 15]
for ___ in ___:
print(temp)Press Run to see the result. The program prints the letters of the word name instead of the stored name. Fix it so it prints the letters of Salma, one per line.
Hint
Remove the quotes around the variable name.name = "Salma"
for letter in "name":
print(letter)Press Run to see the result. You bought school supplies costing 12, 30, 8 and 25 pounds. Add them with a for loop and print Total: 75.
prices = [12, 30, 8, 25]
Press Run to see the result. Count how many times the letter e appears in the word excellence and print just the number.
word = "excellence"
Press Run to see the result. Key points
for v in [a, b, c]:the variable v takes each value in order.- You can store the values in a variable and put its name after
in, without quotes. for letter in "text":goes through the text letter by letter.