Introduction to Python : Loops

Loops

Loops are blocks of code that are used to execute a set of instructions repeatedly over a sequence or as long as a condition remains true. There are two types of loops in Python:

For...in loop

The for...in loop is used to execute a set of statements as we iterate over a sequence or list.

for i in [1, 2, 3, 4]:
   print(i + 1)

This simple program will output 2, 3, 4, and 5. On the first iteration, 'i' takes the value of 1 in the list and therefore outputs 2 (which is 1+1). In the second iteration, 'i' becomes 2 and therefore outputs 3 (2 +1), and so forth until we are at the end of the list.

While loop

The 'while' loop is used to execute a block of code as long as a condition remains true. Example:

x = 5
while x < 8:
   print(x)
   x = x + 1

This program will print 5, 6, and 7 since 'x' is initially equal to 5 which is less than 8. 'x' then becomes 6, 7 and 8 on subsequent iterations since 1 is added to the value of 'x' on each iteration. Once 'x' becomes 8, the condition fails (8 < 8 becomes False) and therefore the loop terminates.


course logo
Introduction to Python
Number of sections:
11
Content length:
Delivery formats: