5  Loops and conditionals

In programming often times there is a requirement that a particular set of instructions is required to be repeated certain number of times. This can be easily achieved using loops. These statements execute a code block repeatedly for specified number of times or until a condition is met.

5.1 For loop

The most common loop that is used to repeat a block of code for fixed number of times is for loop. The example below show iterating through all the elements of a list.

list_of_numbers = [1, 2, 3, 4, 5] 
for x in list_of_numbers:
    print(x*2)
print("Done")
2
4
6
8
10
Done

The for statement begins with the for keyword which is followed by a variable name (x in the example above). This variable would store the different elements in the list as the loop progressess. The in keyword connects the variable with the list and finally we have the list that we want to iterate. The colon (:) at the end is required. It indicates the begining of the block of statements that would be part of the for loop. Next, we have a set of statement that needs to executed for each element of the list. The statement that are part of the for loop must begin with indentation (tab or some spaces). In the example above, the print(x*2) statement is part of the for loop (since it is indented) while the print("Done") statement is not part of the for loop since it is not indented. There must be atleast one statement which is part of the for loop (i.e. atleast one statement that starts with indentation).

5.2 Conditionals

To test a particular condition, if statement is used with an argument having a Boolean operator. Multiple conditions can be tested in one code block using elif. The else keyword take no argument such that its code block gets executed when the if condition (and elif) conditions are return False. Just like for loops, the mandatory requirement of colon (:) and indentation applies in the case of if-else conditions.

x = 5
y = 6

if(x>y):
    print("X is greater than Y")
else:
    print("X is less than Y")

Quiz: Write a program that takes two numbers as input and prints the result of their comparison. The code should consider the case when the two numbers are equal.

Show answer
x = 5
y = 5

if(x>y):
    print("X is greater than Y")
elif(x<y):
    print("X is less than Y")
else:
    print("X is equal to Y")

5.3 While loop

While loop is another frequently used construct to perform task repeatedly when the number of iterations is not fixed. This loop is executed till certain condition is met irrespective of number of iterations.

While expression:

    code block

While loop implicitly has if conditional statement.

x = 5
while(x>2):
    print(x)
    x = x-1
print("Loop is over")
5
4
3
Loop is over

When writting a while loop you must ensure that the condition is met at some point within the loop otherwise the loop will iterate infinitely. E.g. in the above code if the condition within while loop is changed to x>2 then it result in an infinite loop.

5.4 Controlling the execution of loops

Many a times it is require to skip the execution of loop for certain steps or to terminate the loop altogether. Python has some reserved keyword to facilitate this task. continue can be used to jump to subsequent iteration of the loop and break can be used to end the loop.

for x in range (1,10):
    if (x == 5):
        continue
    print(x)
print("Done")
1
2
3
4
6
7
8
9
Done
for x in range (1,10):
    if (x == 5):
        break
    print(x)
print("Done")
1
2
3
4
Done

Quiz: Take a list of first 10 numbers and print the square for even numbers.

Show answer
for x in range(1,11):
    if(x%2 == 0):
        print(x**2)
    else:
        continue