- Intro Powtoon
- Repeat a number times
- Keeping Count
- Loop through a list
For i in range(n):
Let’s say we wanted to print out the word “Hello” 3 times, we could just call the print() function 3 times, like this:
This is nice and easy, and is fine if you just want to do it 3 times – but what if you need to repeat the print statement 10 times, or 100 times? Hmmm this is starting to become hard work – surely there must be a easier way?
We can use a for loop!
(Notice that the line of code that is to be repeated is indented(has 4 spacers before it, this is your way of telling the computer that you want to repeat these lines of code)
But this is only one line of code less that the line above and requires a bit of extra thinking – is it really worth it? Well in this instance it probably isn’t, but what about that 100 times repeat?
Now the efficiency ( and readability) or loops really comes in to play.
Have a go at the following practice examples:
Breaking out of a look
Sometimes we want to stop looping through a for loop if a variable achieves a certain value or if an event happens. In this situation we need to use the break statement.
Here is a slightly longer example