Learning Outcomes:

Upon successful completion of this lesson, you will be able to:

Mark Zuckerburg teaches Repeat Loops (about 2 mins)

In our daily life, we often need to repeat steps to solve a problem. For example, to record the test scores of 20 students on a piece of paper, the lecturer needs to write down the name, followed by the score of the student twenty times. This is similar to repeating the steps in a program, which is known as the loop control. In programming, we can construct loops using variables that change each time they iterate through the loops.


Lesson 1 of 12: Count-controlled Loop

for loop is a count-controlled loop. The syntax of the for loop is:

for <variable> in <sequence>: <statements>

Example.png

Example

For explanation of this example, view the first 4 mins this video:

For Loops in Python (about 10 mins)

Stop after 4 mins.

Example 2.png

Example

What is the output of this program?

Instead of using range(), the for loop can iterate with a list of elements in [ ].

Let's trace the program to get the output.

count output
1st iteration

2nd iteration

3rd iteration

4th iteration

5th iteration | 5

4

3

2

1 | 5 Stop! 4 Stop! 3 Stop! 2 Stop! 1 Stop! |

There are two ways to write the for loop:


Knowledge Check

What are the output?