A.2 Loops and if statements

A.2 Loops and if statements#


     In Python, a for loop is a set of programming commands that is executed several times. A for loop is explained here by looping over all the items in a list. There are two syntax rules for defining a for loop. First, a colon (:) must always terminate the line that starts with for, and second, the lines of code that must be executed during each step of the loop must all be indented. This is illustrated in the following example, in which the variable item takes on the value of each element in the list alist during the for loop. The first line after the for statement is indented, which means that this line is executed every time Python loops through the list. In this example, Python prints the value as well as the variable type of item for pass through the loop

for item in alist:
    print(item, 'has type', type(item))
Dupuit has type <class 'str'>
0 has type <class 'int'>
2.3 has type <class 'float'>
12 has type <class 'int'>

      There is no explicit command that marks the end of the code that must be executed during a loop. Instead, Python’s interpreter infers this based on the indentation. Proper indentation is thus essential as it controls the way the code behaves. This helps tremendously in creating neat, readable scripts. The length of the indentation is arbitrary, as long as it remains the same; the default is four spaces, so use that.
      Looping over the elements of a list is a very pythonic way of doing things. Programmers using other languages may be used to loops that get executed a certain number of times. This is possible too and is typically done using the range command. In the following example, range(4) creates 4 numbers, from 0 up to (but not including) 4

for i in range(4):
    print(f'Step {i}')
Step 0
Step 1
Step 2
Step 3

The range(n) command creates a sequence with n numbers to iterate over, starting at 0. range can optionally be defined by specifying a starting value (the default is zero) and a step (the default step is 1). So a range starting at -3 and stopping before the counter reaches +3 with steps of 2 is defined as

for k in range(-3, 3, 2):
    print(k)
-3
-1
1

      Python also provides the enumerate function, which generates an index counter as it loops through a list. This can be useful for example when the corresponding items in another list have to be modified during the loop. In the following example, the strings in the list names are combined to full names using the strings in the list last_names. By including enumerate() in the line that starts the for loop, a counter i is created so that each time the for loop steps to the next element in the list last_names, i is incremented by 1. Notice the syntax: The counter i is a user-defined variable name that precedes the name that is used within the for loop for the active element in the list (last_name in this case).

names = ["Henry", "Willem", "Alexander"]
last_names = ["Darcy", "Badon Ghyben", "Herzberg"]
print("First names", names)
for i, last_name in enumerate(last_names):
    names[i] = names[i] + " " + last_name
print("Full names", names)
First names ['Henry', 'Willem', 'Alexander']
Full names ['Henry Darcy', 'Willem Badon Ghyben', 'Alexander Herzberg']

Conditional statements#

     Conditional statements (also called if statements) can be used to control the flow of a program depending on whether or not certain conditions are met. Just like with the for loop, a colon must be typed at the end of the line starting with if, and the lines that must be executed if the evaluated condition is true must be indented. There is no specific command to end the if statement: As with for loops it is inferred from the indentation.
      In the next code cell, it is checked if the list alist actually contains elements by calling the len function, which returns the number of items (zero for an empty list).

alist = [] # Defines an empty list
if (len(alist) == 0):
    print ("alist contains no elements")
alist contains no elements

Note that a double equal sign is used for the comparison (since a single equal sign is reserved for value assignment). Other comparison operators in Python include the following (note that the comparisons return a Boolean variable type, which can be printed to the screen).

a = 4
print(a <= 4) # a is smaller than or equal to 4
print(a == 4) # a is equal to 4.
print(a >= 4) # a is larger than or equal to 4
print(a != 4) # a is not equal to 4
True
True
True
False

Conditions can be compounded with the and or or statements, with parentheses for readability

a = 7
if (a > 3) and (a < 8):
    print('The value of a is', a)
The value of a is 7

      In the following code example, the if statement is placed inside a for loop to determine what message is printed to the screen. The message varies according to the value of the loop variable i. The if statement now also includes the elif and else commands (note how the indentation works)

for i in range(-1, 3):
    if i < 0:
        print(i, 'is negative')
    elif i == 0:
        print(i, 'is zero')
    else:
        print(i, 'is positive')
-1 is negative
0 is zero
1 is positive
2 is positive