Python for loops: repeat code for each item
A for loop runs the same lines of code once for each item in a sequence, so you write the instruction once instead of many times.
Open in PyPad to change it and keep your own copy.
How it works
Each time round the loop, the name after for holds the next item, and the indented lines below it run. The loop stops when the items run out.
range(1, 6)gives the numbers 1 to 5. The end number is left out.- A list such as
fruitsgives its items one at a time, in order. - Indentation matters: only the indented lines belong to the loop.
Try changing it
- Change
range(1, 6)so it counts to 10. - Add another fruit to the list and run the cell again.
- Change the last example so it adds up your own prices.
A common mistake
Forgetting the indentation, or the colon at the end of the for line, gives an error. Python needs both to know which lines to repeat.