PythonLesson 7 of 16
for loops and range() in Python
A for loop walks through a list and does the same thing for each item. Three tracks or three thousand, the code stays just as short.
Key points
- for x in my_list: gives x each value in turn
- range(5) gives 0, 1, 2, 3, 4; range(1, 6) gives 1 to 5
- A third argument is the step: range(3, 0, -1) counts down
- total += price is short for total = total + price
- range(len(items)) gives indexes, handy for walking two lists together
Example
playlist = ["Intro", "Sunrise", "Run"]for song in playlist: print("Playing", song) for n in range(3, 0, -1): print(n)print("Go!")The indented lines are the loop body and repeat each time. print("Go!") has no indent, so it runs once, after the loop.
Task
How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.Print the receipt: each item as 1. tea - 150 (numbered from one), then the total after the loop. Collect the sum in total.
Output
What your program prints appears here.