Loops#

Life is full of routines. In programming we also do lots of repetitive tasks. In order to handle repetitive task programming languages use loops. Python programming language also provides the following types of two loops:

  1. while loop

  2. for loop

While Loop#

We use the reserved word while to make a while loop. It is used to execute a block of statements repeatedly until a given condition is satisfied. When the condition becomes false, the lines of code after the loop will be continued to be executed.

while condition:
    code goes here
count = 0
while count < 5:
    print(count)
    count = count + 1
0
1
2
3
4

In the above while loop, the condition becomes false when count is 5. That is when the loop stops. If we are interested to run block of code once the condition is no longer true, we can use else.

while condition:
    code goes here
else:
    code goes here
count = 0
while count < 5:
    print(count)
    count = count + 1
else:
    print(count)
0
1
2
3
4
5

The above loop condition will be false when count is 5 and the loop stops, and execution starts the else statement. As a result 5 will be printed.

Break and Continue - Part 1#

Break: We use break when we like to get out of or stop the loop.

while condition:
    code goes here
    if another_condition:
        break
count = 0
while count < 5:
    print(count)
    count = count + 1
    if count == 3:
        break
0
1
2

The above while loop only prints 0, 1, 2, but when it reaches 3 it stops.

Continue: With the continue statement we can skip the current iteration, and continue with the next:

while condition:
    code goes here
    if another_condition:
        continue
count = 0
while count < 5:
    if count == 3:
        count = count + 1
        continue
    print(count)
    count = count + 1
0
1
2
4

The above while loop only prints 0, 1, 2 and 4 (skips 3).

For Loop#

A for keyword is used to make a for loop, similar with other programming languages, but with some syntax differences. Loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string).

For loop with list#

for iterator in list:
    code goes here
numbers = [0, 1, 2, 3, 4, 5]
for (
    number
) in (
    numbers
):  # number is temporary name to refer to the list's items, valid only inside this loop
    print(number)  # the numbers will be printed line by line, from 0 to 5
0
1
2
3
4
5

For loop with string#

for iterator in string:
    code goes here
language = "Python"
for letter in language:
    print(letter)

for i in range(len(language)):
    print(language[i])
P
y
t
h
o
n
P
y
t
h
o
n

For loop with tuple#

for iterator in tuple:
    code goes here
numbers = (0, 1, 2, 3, 4, 5)
for number in numbers:
    print(number)
0
1
2
3
4
5

For loop with dictionary#

Looping through a dictionary gives you the key of the dictionary.

for iterator in dict:
    code goes here
person = {
    "first_name": "Aurora",
    "last_name": "Luna",
    "age": 6,
    "country": "Indonesia",
    "skills": ["JavaScript", "React", "Node", "MongoDB", "Python"],
    "address": {"street": "Jl. Jalan", "zipcode": "123456"},
}

for key in person:
    print(key)

for key, value in person.items():
    print(key, value)  # this way we get both keys and values printed out
first_name
last_name
age
country
skills
address
first_name Aurora
last_name Luna
age 6
country Indonesia
skills ['JavaScript', 'React', 'Node', 'MongoDB', 'Python']
address {'street': 'Jl. Jalan', 'zipcode': '123456'}

For loop with set#

for iterator in st:
    code goes here
it_companies = {"Facebook", "Google", "Microsoft", "Apple", "IBM", "Oracle", "Amazon"}
for company in it_companies:
    print(company)
Amazon
Facebook
Apple
Oracle
IBM
Microsoft
Google

Break and Continue - Part 2#

Short reminder: Break: We use break when we like to stop our loop before it is completed.

for iterator in sequence:
    code goes here
    if condition:
        break
numbers = (0, 1, 2, 3, 4, 5)
for number in numbers:
    print(number)
    if number == 3:
        break
0
1
2
3

In the above example, the loop stops when it reaches 3.

Continue: We use continue when we like to skip some of the steps in the iteration of the loop.

for iterator in sequence:
    code goes here
    if condition:
        continue
numbers = (0, 1, 2, 3, 4, 5)
for number in numbers:
    print(number)
    if number == 3:
        continue
    (
        print("Next number should be ", number + 1)
        if number != 5
        else print("loop's end")
    )  # for short hand conditions need both if and else statements
print("outside the loop")
0
Next number should be  1
1
Next number should be  2
2
Next number should be  3
3
4
Next number should be  5
5
loop's end
outside the loop

In the example above, if the number equals 3, the step after the condition (but inside the loop) is skipped and the execution of the loop continues if there are any iterations left.

The Range Function#

The range() function is used to create a list of numbers. The range(start, end, step) takes three parameters: starting, ending and increment. By default it starts from 0 and the increment is 1. The range sequence needs at least 1 argument (end).

# Creating sequences using range
lst = list(range(11)) 
print(lst) # [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
st = set(range(1, 11))    # 2 arguments indicate start and end of the sequence, step set to default 1
print(st) # {1, 2, 3, 4, 5, 6, 7, 8, 9, 10}

lst = list(range(0,11,2))
print(lst) # [0, 2, 4, 6, 8, 10]
st = set(range(0,11,2))
print(st) #  {0, 2, 4, 6, 8, 10}

# Looping through range
for iterator in range(start, end, step):
for number in range(11):
    print(number)  # prints 0 to 10, not including 11
0
1
2
3
4
5
6
7
8
9
10

Nested For Loop#

We can write loops inside a loop.

for x in y:
    for t in x:
        print(t)
person = {
    "first_name": "Aurora",
    "last_name": "Luna",
    "age": 6,
    "country": "Indonesia",
    "skills": ["JavaScript", "React", "Node", "MongoDB", "Python"],
    "address": {"street": "Jl. Jalan", "zipcode": "123456"},
}

for key in person:
    if key == "skills":
        for skill in person["skills"]:
            print(skill)
JavaScript
React
Node
MongoDB
Python

For Else#

If we want to execute some message when the loop ends, we use else.

for iterator in range(start, end, step):
    do something
else:
    print('The loop ended')
for number in range(11):
    print(number)  # prints 0 to 10, not including 11
else:
    print("The loop stops at", number)
0
1
2
3
4
5
6
7
8
9
10
The loop stops at 10

Pass#

In python when statement is required (after semicolon), but we don’t like to execute any code there, we can write the word pass to avoid errors. Also we can use it as a placeholder, for future statements.

for number in range(6):
    pass

You established a big milestone, you are unstoppable. Keep going! Now do some exercises for your brain.

Exercises#

Exercises: Level 1#

  1. Iterate 0 to 10 using for loop, do the same using while loop.

  2. Iterate 10 to 0 using for loop, do the same using while loop.

  3. Write a loop that makes seven calls to print(), so we get on the output the following triangle:

      #
      ##
      ###
      ####
      #####
      ######
      #######
    
  4. Use nested loops to create the following:

    # # # # # # # #
    # # # # # # # #
    # # # # # # # #
    # # # # # # # #
    # # # # # # # #
    # # # # # # # #
    # # # # # # # #
    # # # # # # # #
    
  5. Print the following pattern:

    0 x 0 = 0
    1 x 1 = 1
    2 x 2 = 4
    3 x 3 = 9
    4 x 4 = 16
    5 x 5 = 25
    6 x 6 = 36
    7 x 7 = 49
    8 x 8 = 64
    9 x 9 = 81
    10 x 10 = 100
    
  6. Iterate through the list, [‘Python’, ‘Numpy’,’Pandas’,’Django’, ‘Flask’] using a for loop and print out the items.

  7. Use for loop to iterate from 0 to 100 and print only even numbers

  8. Use for loop to iterate from 0 to 100 and print only odd numbers

Exercises: Level 2#

  1. Use for loop to iterate from 0 to 100 and print the sum of all numbers.

    The sum of all numbers is 5050.
    
  2. Use for loop to iterate from 0 to 100 and print the sum of all evens and the sum of all odds.

    The sum of all evens is 2550. And the sum of all odds is 2500.