Module 3 - Section 1 - Loops

After the completion of this module the students will be able to:
  • state the need of using loops
  • use the for loop
  • create code using nested loops
  • calculate a sum of numbers using loops

3.1.1 - Range

What is a loop in programming? In computer programming, a loop is a sequence of instructions that is continually repeated until a certain condition is reached.

What will we do to print 10 times our best friends name? We could write the following code 10 times:

print("My best friends name is Nick")
print("My best friend's name is Nick")
print("My best friend's name is Nick")
print("My best friend's name is Nick")
print("My best friend's name is Nick")
print("My best friend's name is Nick")
print("My best friend's name is Nick")
print("My best friend's name is Nick")
print("My best friend's name is Nick")
print("My best friend's name is Nick")


Instead we can order the computer to repeat the command 10 times.

First of all we have to learn the range command. When we write range(10), python generates a list of numbers, which is generally used to iterate over with for loops.

So range(5) contains 5 numbers [0, 1, 2, 3, 4]. In computer languages counting starts from 0 (zero).

If you want to view what is inside a range you can write the command  in CLI

>>> list(range(5))

Try also the following and try to understand what range does

>>> list(range(3,6))     # The result is [3, 4 , 5]

>>> list(range(9,16))   # The result is [9, 10 , 11, 12, 13, 14, 15]

So a list includes numbers starting from the first one until the last one without including the last one and increasing (stepping) them with 1.

If we omit the first number it is the same as writing 0

>>> list(range(5)) # is the same as 

>>> list(range(0,5))

What else can we do with range? Change the step.

Try the following in CLI

>>> list(range(2,20,3))

The first item is 2, the next is 5 (2+3), the next is 8 (5+3) .... and the last one is 17, 20 is not included in the list)

As an exercise try the following code and before execution try to foresee the result :

>>> list(range(1,9,2))

>>> list(range(7))

>>> list(range(7,17,4))

As an exercise write a range command that has 10 numbers.
Of course the easiest is range(10). List it with the command

>>> list(range(10))