Skip to content

Loops

Loop is to repeat part of code a fixed number of times until specific conditions meet for every collection element or infinity.

The following loop features can be distinguished:

  • Execute part of code until conditions are met,
  • Code executed depends by a finite number of circuits (loops),
  • Loops which don't have the end are called infinity loops.

In Python we have two types of loop:

  • loop while,
  • loop for.

Iterations

Iterating it's execution of specific code several times. Programming structure that implement iterations is loop.

In case of infinity iteration, number of repeats is not defined. Code block is executed several time until some condition is met.

In case of defined iteration, code block is repeated specified number of times.

Loop while

Loop while is usually used where number of repeats is not known but there's known condition until it should be executed.

  • Loop execute until <condition> is met.
  • <condition> is check and if it's True, <instructions> are executed, if not False - Python skips code and exectues part after the loop.
  • After execution of while loop, <condition> is checked again, if it's still meet loop execute next time.
  • If <condition> is false, it's possible that loop will not execute part of code even one time.

The general scheme looks like the following:

    while <condition>:
        <instruction_1>
        <instruction_2>
        ...
        <instruction_n>

When we can use loop while?

Repeat until user will not provide number (he can give i.e. letters and we don't know on which time he will provide expected value (number), so how many times loop needs to be executed). Repeat until game player have ammo in a machine gun (we don't know how many times he will shoot, or he will not shoot at all).

Simple example might looks like this. Program will write numbers 1, 2, 3, 4, 5, every in a new line:

    # Execute until n is lower than 5
    n = 0
    while n < 5:
        n += 1  # increment n in every next loop
        print(n)

Loop execution break

In loops there are important key words break and continue.

Command break:

  • Instantly break current loop runs and exits loop.
  • Program leaves loop code and continues the execution of rest code - outside of loop.

Command continue:

  • Instantly break current loop runs and goes to next loop iteration.
  • Before start of iteration <condition> is checked, which determines if next iterations should happen or not.

Example of while loop with break and continue. Program will write number 2 and 3, each in a new line.

    # Execute until n is lower than 5
    n = 0
    while n < 5:
        n += 1  # increment n in every next loop
        if n == 4:  # if n is equal 4 break loop
            break
        if n == 1:  # if n is equal 1, start new iteration
            continue
        print(n)

Loop for

The general scheme of for looks like the following:

    for <var> in <iterable>:
        <instruction>
  • <iterable> it's collection of variables/values that we can use to iterate - i.e. list.
  • To create loop code block we will use code indentations.
  • For loop body is executed for every collection element <iterable>.
  • Variable <var> gets value of every collection element <iterable> and it's available in loop iteration.

Program will write all element from list.

    animals = ["Dog", "Cat", "Fish"]

    # Write all animals from list
    for animal in animals:
        print(animal) # Write one animal one by one

Idea of for loop is easy. In above example, there's an iteration by animals list elements. In each run variable gets next value from the list. In first run variable animal gets string "Dog". In second: "Cat". In third "Fish". If list would be empty loop would not execute because there's nothing to iterate on (list doesn't have any elements).

Commands break and continue are available in for loop, the same as it was in while loop.

Function range()

Function range is used to generate list of numbers. Here's what her signature looks like:

range(start, stop, step)

  • Function range() returns iterated object that contains numbers from 0 to start, if number start is provided as parameter.
  • Function range() returns iterated object that contains numbers from start to stop without number stop, if start and stop are set.
  • Optionally we can add third parameter step that determines how many values should be skip between loops.

Examples of range function:

    # Write 0, 1, 2 in new lines
    for i in range(3):
        print(i)

    # Write -3, -2, -1, 0 in new lines
    for i in range(-3, 1):
        print(i)

    # Write 0, 3, 5, 7, 9 in new lines
    for number in range(3, 11, 2):
        print(number)

    # Write -1, -2, -3 in new lines
    for number in range(-1, -4, -1):
        print(number)

Function enumerate()

Usually we want to know current loop run number when we use collection. Function enumerate accepts collection as a parameter and returns tuple with two values: element index and current element from collection.

    fruits = ["apple", "banana", "lemon"]

    for index, fruit in enumerate(fruits):
        print(f"Fruit: {fruit}, indexed: {index}.")

Using range function in loop for to get number of iteration is recognized as non-python way. If we iterate on some collection and we want to know, which run is it, we should use enumerate function.

Lists, collections and compound dictionaries

In example, we wat to create a list of numbers from 0 to 999. The list is to long to write it manually. We can populate it with values using for loop or create it using list comprehension mechanism.

Here is an example of list based on comprehension list mechanism:

    # List populated in loop for
    numbers = []
    for i in range(1000):
        numbers.append(i)

    print(len(numbers))  # Write 1000

    # Comprehension list
    numbers = [i for i in range(1000)]
    print(len(numbers))  # Write 1000

In the same way we can use comprehension dictionary mechanism to initiate dictionary.

    keys_and_values = [(1, 'a'), (2, 'b'), (3, 'c')]
    dictionary = {number: letter for (number, letter) in keys_and_values}

In the same way we can collect sets:

    numbers = {number for number in range(0, 10)}