Loops
This lesson will introduce loops in Python.
We'll cover the following...
Why loops?
Many times, during programming, we have to repeat the same task a number of times. For instance, we have a list of numbers and we want to double every number in it. Here, we want to perform the same task for every item on our list. This is where loops come in handy. Loops are used to execute the same block of code a fixed number of times.
There are two kinds of loops in Python.
- The
for
loop - The
while
loop
The for
loop
A for
loop uses an iterator to traverse a sequence, e.g. a range of numbers, the elements of a list, etc. In simple terms, the iterator is a variable that goes through the list. The iterator starts from the beginning of the sequence. In each iteration, the iterator updates to the next value in the sequence. The loop ends when the iterator reaches the end.
In a for
loop, we need to define three main things:
- The name of the iterator
- The sequence to be traversed
- The set of operations to perform
The loop always begins with the for
keyword. The body of the loop is indented ...