Counting Loops

Challenge 3-2: Loops

Counting loops repeat a certain number of times - they keep going until they get to the end of a list.

>>> for mynum in [1, 2, 3, 4, 5]:

print("Hello", mynum)


Hello 1

Hello 2

Hello 3

Hello 4
Hello 5

Notice the list of integers in the very first line of code: [1, 2, 3, 4, 5]

What this loop is doing is going over that list, and for each item in the list, it's printing the word "Hello" along with that item.

mynum is a variable - for each item in the list, a new value is assigned to it.

The loop starts with the first item in the list and gives a value of 1 to mynum. Python then takes that value and prints out 'Hello 1'.

Then the loop goes back up to the next item in the list. The value of mynum becomes 2, Python prints out 'Hello 2', and so on.

This keeps going until Python gets to the last item in the list - the number 5. After that, there are no more items, so the loop stops running.

The for keyword is used to create this kind of loop, so it is usually just called a for loop.