- Starter
- Intro Powtoon
- Repeat a number times
- Keeping Count
- Loop through a list
- Break
- Challenges
- Resources
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.
Practice:
Have a go at the following practice examples:
Keeping count
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.
Super simple!
Example
Here is a slightly longer example
Challenge 21
Challenge 22
Challenge 23
Challenge 24
Challenge 25
Challenge 26
Challenge 27
Challenge 28
Challenge 29
Challenge 30
Challenge 31