Lesson 8: For Loop

Loops are very powerful repetition structures (sometimes also called flow charts) in Python that help you repeat a task or function for a number of times. In this lesson we will particularly look at “For Loops”.

It’s best explained over an example:

>>> for <iterator> in <iterable>:
>>>     <execute task>

You have 3 values to keep in mind among with some structural rules.

  • start your for loop with “for”
  • next line should be indented
  • iterator is a variable name you make up for your iteration (repetition)
  • iterable is a sequence (usually a list, tuple, string, range function or a dictionary)
  • do something is where you type your function. It can be as simple as printing “Hello World!” or a more complex task.

Function : N/A

No new function will be introduced in this lesson.

Used Where?

Loops are great tools for handling repetitive tasks. They can be used for:
  • Processing each element of a sequence
  • Printing each element of a sequence
  • Executing a program for the number of each element in a sequence
  • Accumulating data

To give just a few examples.

Syntax do(s)

1) First line starts with for

2) There is a colon(:) at the end of first line

2) After first line following lines should be indented

Syntax don't(s)

1) Don’t forget the colon (:) at the end of the first line

2) Don’t forget the indent after the first line

Example 1

>>> for iter in range(3):
>>>     print(“Hello World!”)

Hello World!”
Hello World!”
Hello World!”

In this example <iter> is just a variable we named. range(3) has 3 elements (0,1,2). So for each value (or iter) “Hello World!” is printed once. 

Example 2

>>> a = 10
>>> for iter in range(5):
>>>     a = a+5

>>> print(a)

35

We have created a variable with initial value of 10. And each time the loop runs, a gets assigned to its initial value plus 5.

In the next iteration its initial value becomes plus 5 and so on. After 5 total iterations loop stops and final value of a is 35.

Also print() function is not inside the loop so nothing gets printed during the loop, but a’s value becomes updated behind the curtain with each iteration.

Tips

1- For loop is usually more useful when you know the exact iteration time before the loop. When you’re iterating through sequences like lists, tuples, dictionaries, strings and ranges, since you know the length of the sequence already it usually makes more sense to utilize a for loop.

Example 3

So each time iter takes a value, our task gets executed. How about printing the value iter takes as a task?

>>> for iter in range(4):
>>>     print(iter)

0
1
2
3
4

Advanced Concepts (Optional)

Nested For Loop

1- In some situations you might need a nested loop structure. We have previously seen that lists can be consisted of many type of different data including other lists. Let’s see an example of nested list and nested for loop.

Example 5

>>> a = [[1,2,3], [“land”, “sea”, “sky”]]
>>> for i in a:
>>>     for j in i:
>>>         print(j)

1
2
3
land
sea
sky

In the first iteration, i gets assigned to first element in a ([1,2,3]) and then j gets assigned to each element in i (1,2,3)

In the second iteration, i gets assigned to second element in a ([“land”, “sea”, “sky”]) and then j gets assigned to each element in i (“land”, “sea”, “sky”)

Example 6

And everything until last 2 elements with steps of 2

>>> a = list(range(10))
>>> print(a[:-2:2])

[0, 2, 4, 6]

Exercise 8

Lesson 9

While Loop

Richard_Redgrave_-_The_Emigrants'_Last_Sight_of_Home


Richard Redgrave

The Emigrants Last Sight of Home

The Emigrants Last Sight of Home by Richard Redgrave