Skip to content
Learnearn.uk » Python Unit Home » For loops

For loops


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:

Practice 1

 

Practice 2
Practice 3

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

demo

Challenge 21

ch21

Challenge 22

ch22

Challenge 23

ch23

Challenge 24

ch24

Challenge 25

ch25

Challenge 26

ch26

Challenge 27

ch27

Challenge 28

ch28

Challenge 29

ch29

Challenge 30

ch30

Challenge 31

ch31


For loops Kahoot

 

Let's learn Python YouTube Video -Loops

Let’s learn Python YouTube Video -Loops