Control Statements

Control statements provide mechanisms to control the execution of a program based on certain conditions. Python provides conditional if statement and loop structures - while and for.

Control statements become part of a compound statement and should all be executed together based on the control statement's conditional result.

Before we proceed with the control statements, let us understand built in function input and int in Python along with compound statements

Consider the example below:

a = int(input("Please enter a number"))
print(a)

Output: what ever number you entered in the input box.

When you run the above example, you are prompted for an input and that input is read by input function which returns a line of string from the console. int() function receives the string result from input function and returns corresponding integer value of the string to variable a. If you do not input a number in the console, then a ValueError is thrown as int function cannot convert any other input to integer other than an integer. Note that even though you input a number from the keyboard, input function still returns that number as a string and the int function converts that string to a number.

Python provides a number of such built in functions and here link to the official documentation: https://docs.python.org/3/library/functions.html

Compound Statements

So far you studied simple statements in Python. A simple statement consisted of one single statement which had no logic control relation to other statements before or after that statement. Simple statements are stand alone statements which are syntactically correct to use individually.

A compound statement on the other hand, contain groups of statements. They span multiple lines and will generally have indentation which marks the groups to be executed as one block together. Although you may write a compound statement without indentation, it is recommended to use indentation. When you do use the indentation, Python is strict about the number of indents (should be 4) relative to its predecessor statement. If you do not indent correctly you get IndentationError

1. Conditional if statement

A very common conditional that is used in almost all programming languages is an if statement.

Before you proceed further on if let us understand the relational and logical operators available which are used in if and while statements.

The following are the relational operators in Python which all evaluates to True or False based on the expression. The two operands 9 and 8 shown below can be replaced by any expression consisting of one or more variables.

Operator name Notation Example Result
Greater than > 9 > 8 True
Less than < 9 < 8 False
Greater than or equal to >= 9 >= 8 True
Less than or equal to <= 9 <= 8 False
Equal to == 9 == 8 False
Not equal to != 9 != 8 True

The following are the logical operators in Python

Operator name Notation Example Result Comment
logical AND and
9>8 and 5>4
True Returns True if both expressions on either side of and evaluate to True. This operator evaluates the second expression only if the first expression evaluates to True
logical OR or 8>9 or 5>4 True Returns True if either one of the expressions on either side of or evaluate to True. This operator evaluates the second expression only if the first expression evaluates to False
logical NOT not not 9>8 False Reverses the value of the Boolean expression

Now let us take a grading calculation as an example below to use the if operator:

score = int(input("Please enter your score: "))
if score > 90:
    print("Congratulations! you scored an 'A' grade")
elif score > 80:
    print("Congratulations! you scored a 'B' grade")
elif score > 70:
    print("Congratulations you scored a 'C' grade")
else:
    print("Sorry you failed.")

In the above program, you first get the input from the user, and then evaluate the first conditional if (score > 92) which is of the form

if (conditional expression which evaluates to True or False) :

conditional expression is made up of one or more logical or relational expressions including combinations of both types

A colon ':' should follow immediately after the conditional expression. If the conditional expression evaluates to True, then the program of execution starts from the indented statements after the : If the conditional evaluates to False then the program of execution skips the indented block after : and proceeds to elif statement and checks for conditional again. The same logic is applied on all other conditionals all the way till the else statement. The last else statement is executed if all conditionals expression above evaluated to False.

else is optional in an if statement.

2. The while loop

The while statement is used when the program of execution has to repeat a set of statements till a conditional is true:

repeat = True
while repeat:
    user_input = input("Please input anything to continue. " +
                       "If you want to quit, input 'quit' in small case ")
    print(user_input)
    if (user_input == 'quit'):
        print("OK have a good day!")
        repeat = False  #  Loop stops here as the conditional becomes False

In this example, you first initialize variable repeat to True. The while construct needs a conditional expression which evaluates to True, similar to if, however in a while, conditional is tested after every iteration. If the conditional expression is True, then the indented block of compound statements after the : is executed, and is repeated continuously till the conditional becomes False.

In this example, the conditional expression is a variable which has a value of True to begin with. The user is asked to key in any value in every iteration. If the value keyed in by the user is quit then the variable repeat is set to False and the while loop ends at that time. Till then the entire block of statements for the while is repeated.

Points to note

  • Although it is recommended to always indent the block of code for a conditional, sometimes you will see code in which all statements are in one line, separated by a semicolon ; The different variations that are all possible are shown below for the if block in the previous example:
  • If you use semicolor at the end of every statement it does not hurt but in Python it is not required.
  • The program of execution is in an infinite loop in the above example till the user enters quit. You should always exercise caution with infinite loops as the processor is constantly working on your code without respite and thus using the necessary computing power on your machine till the loop ends.
  • When the program is running a block of code, you see a * on the side bar of Jupyter Notebook.
if (user_input == 'quit'): print("OK have a good day!"); repeat = False
if (user_input == 'quit'): 
   print("OK have a good day!"); repeat = False

3. The for loop

The for statement is another way to create a compound statement block which will be repeated a given number of times. The statements in the for block will be executed in a sequence for a given number of predetermined times.

for x in range(0,3):
    # Executes the below statement 3 times, one for each number in the range
    print("This is really fun! Value of x=" + str(x))

Output:
This is really fun!
This is really fun!
This is really fun!

Optional else statement which can be used with both while and for

If you use the optional else statement after compound block, then once the conditional is False in case of while or once the iteration count ends in case of for, the else is executed.

for x in range(3):
    print(x)
else:
    print('Value of x after all the iterations: x = %d' % (x))

Output:
0
1
2
Value of x after all the iterations: x = 2

One of the very popular uses of a for block is in iterating collections:

scores = [50, 80, 90, 100]
for score in scores:
    print(score)

Output:
50
80
90
100

In case of strings you can iterate on each letter

language = 'Python'
for x in language:
    print(x)

Output:
P
y
t
h
o
n

Looping over a list of lists

multi_list = [ 
     [1, 2, 3], 
     [4, 5, 6], 
     [7, 8, 9]
     ]
for list in multi_list:
    print(list)

Output:

[1, 2, 3]
[4, 5, 6]
[7, 8, 9]

break statement

Any loop, both for and while can be broken off before it completes the required number of iterations of the loop (including loops at any inner level) by using break statement.

multi_list = [ 
     [1, 2, 3], 
     [4, 5], 
     [7, 8, 9]
     ]
for list in multi_list:
    print(list)
    if (len(list) == 2):
        break

Output:

[1, 2, 3]
[4, 5]

In the above example, you break the iteration midway with the conditional if statement, before it gets to the third iteration.

continue statement

The continue statement will skip the rest of the statements after the continue statement in the loop block and continues with the next iteration of the loop.

Here is a program to collect all even numbers from 1 to 10 (excluding 10)in a list and print it in the end and print all odd numbers as they are found:

list=[]
for num in range(1, 10):
    if num % 2 == 1:
        print("Found odd number", num)
        continue  # If odd number continue
    list.append(num)
print(list)

Output:

Found an odd number 1
Found an odd number 3
Found an odd number 5
Found an odd number 7
Found an odd number 9
[2, 4, 6, 8]

Note that list.append(num) is not invoked when it finds an odd number because of continue

enumerate

When it comes to collections, you can use enumerate to get tuples of index and element, from any collection. Here is an example;

list = [1,2,3,4]
for i in enumerate(list):
    print(i)

output:

(0, 1)
(1, 2)
(2, 3)
(3, 4)

Notice you receive a tuple containing the index and the element from the list. You can replace the above list with a set, tuples, zip etc..

If you want to get index and element separately, you can use enumerate in the below way;

myset = {('a', 1),('b',2),('c',3)}

for i,j in enumerate(myset):
    print(i ,j)

output:

0 ('b', 2)
1 ('c', 3)
2 ('a', 1)

In the above, i represents the index number and j represents the individual element. Both are printed in the example.

You can use enumerate to iterate lists, tuples, sets and also zip objects. You will learn about the zip next.

Zip and *

You may come across a few other operations in Python programs on the Internet. Although you may not come across the need for these on a regular basis, it is still good to know what they do. You will briefly learn their significance.

Zip

Zip is used to transform multiple collections into a single collection of tuples of respective elements.

list1 = ['a','b','c']
list2 = [1,2,3,4]
zipped = zip(list1,list2)
print(type(zipped))

for i,j in enumerate(zipped):
    print(i ,j)

output:

< class 'zip' >
0 ('a', 1)
1 ('b', 2)
2 ('c', 3)

In the above example you convert two lists of different data types into a zip object containing tuples with elements from each list in the order in which the zip was invoked. If the length of the two lists are different then the zip stops at the length of the shortest list.

A zip object can be enumerated as shown above or you can convert it into a list by using the list function. However once enumerated or converted to a list, the zip object will be empty and cannot be reused. See the example below;

list1 = ['a','b','c']
list2 = [1,2,3,4]
zipped = zip(list1,list2)
tuple_list = list(zipped);

for i in tuple_list:
    print(i)   # this will print the tuples.

for i,j in enumerate(zipped):
    print(i,j)  # this will not be invoked as the zipped is empty

zip can be used on any collection; set, tuple, list etc.. One point to note in set is, since set does not maintain the order, you will not be sure which elements form the resultant tuple.

* for Unpacking Collections

Asterisk (*) performs argument unpacking. This is used with an enclosing function. Here is an example;


def multiply(a,b):
    return a*b

print(multiply(*[2,3]))

output:

6

Note however that, you cannot use asterisk by itself without an enclosing function. Although the example shows a list, you can replace the list with any collection object like tuple, set etc..

** for Unpacking Dictionary

You can use double asterisk (**) to unpack a dictionary into name, value pairs. Here too it should be used as an argument to a function. Here is an example;

def myfunc(country,state,county):
    print(country,state,county)

my_place = {'state':'Michigan', 
                'county':'Wayne', 'country':'United States',}
myfunc(**my_place)

output:

United States Michigan Wayne

results matching ""

    No results matching ""