How would you use Python to count all numbers between 1 and 10?
Sure, you could do this:
print(1) print(2) print(3) … # and so on untill print(10).
But is there a better way?
How would you print all numbers från 1 to 100? In the same way as above? Sure, it's possible, but that means 100 lines of code. And we're doing almost the same thing on every line, just with a different number.
Repeating code is an important building block in programming. We saw it with rock-paper-scissors in the last chapter in order to play again and again.
Look at the following example:
for i in range(1, 11): print(i)
What happens here? The first word is for - we're telling Python we want to repeat something. We then need to name a variable to use, and finally what interval (or range) we're looping over. In this case from 1 to 11, but we don't include the final number, so really 1 to 10 inclusive. But more on that soon.
After that we list the lines of code we want to repeat once for every value in the interval. Note that these lines are indented, just as for if-statements (and while loops).
When the program starts the loop it create a variable i with the value 1. Then, the line or lines indented are executed. In this case it's print(i), so a 1 is printed.
Then we loop back. The variable i gets the next value in the range, which is 2. The line or lines indented are executed again, but this time print(i) results in printing a 2.
And so on for i=3, up until we've printed 10. After that, the next value is 11 but that's when we stop - we say that the loop terminates.
We don't really need to use this variable i in the print function either. This would also be OK:
for i in range(1, 5): print("Hi there")
This gives us 4 "Hi there", one for each value on i, even though we're not using the variable i.
Note that it's outputs, because the interval goes 1, 2, 3, 4, but stops on 5 before it runs the code inside the loop.
We can also use the variable i for other computations. If we want the 4 times table:
It is common to use i or j as names for the variable in a for-loop, but you can name this almost whatever you want (just like other variables). Remember to use descriptive names, like "result". It makes it easier to keep track of the various parts of one's code.
Loops are a concept that takes some time getting used to, so it's extra important to do the related exercises and try it out yourself to get more comfortable.
In this video, we look at the difference between while loops and for loops, and an example of when we might use them.
- range: Creates an interval that can be used in loops to repeat code, for example all numbers between 1 and 10.
- for-loop: One type of loop/repetition that fits well for a predetermined number of steps.
- while-loop: One type of loop/repetition that fits well when we don't know how many iterations need to run. Can also be used for infinite loops.