Lesson 6: Selection Statements and Flow Control

Learn python programming in 12 lessons


Remember that an algorithm has three main elements which are steps, decisions and repetitions. When we talk of selections, we are referring to statements that require some form of decision to be taken which can alter the program flow. Sometimes these statements need to be repeated over and over until some terminating condition is satisfied.

In Python, decisions are handled by decision structures and one of the most common is the if-else statement. Any example of an if-else statement that checks the persons age and determines if that person is a minor or adult can look like this


if (age < 18):
    print(“Minor”)
else:
    print(“Adult”)

Decision structures make use of relational operators such as seen in the table below
> less than
>= less than or equal to
< greater than
<= greater than or equal to
== equal to
!= not equal to

Note that the condition age<18 will either evaluate to true or false. This implies that conditions are boolean expressions and in Python, they are identified by the literal True and False (take note of the capital letter).

How would you go about arranging the control statements for a grade allocation program that prints the following output based on what marks is entered by the user?
A — 80 - 100
B — 75 - 79
C — 70 - 74
D — 60 - 69
E — 50 - 59
F — 0 - 49

The if statements can look something like this


if (mark > 79 and mark <=100):
    print("A")
if (mark > 74 and mark <=79):
    print("B")
if (mark > 69 and mark <=74):
    print("C")
if (mark > 59 and mark <= 69):
    print("D")
if (mark > 49 and mark <= 59):
    print("E")
if (mark > 0 and mark <=49):
    print("F")
else:
    print("invalid marks")

It is important that you notice that it is probably best to check if a valid grade is entered at the beginning of the if statements because this would save time and avoid checking the rest of the control statements.
Another improvement is to make use of the elif keyword which stands for else-if. With all these improvements, the program would look like this


#Name this file DistributeGrade.py

def allocateGrade(mark):
    if (mark < 0 or mark > 100):
        print("Invalid mark!")
    elif (mark > 79):
        print("A")
    elif (mark > 74 and mark <=79):
        print("B")
    elif (mark > 69 and mark <=74):
        print("C")
    elif (mark > 59 and mark <= 69):
        print("D")
    elif (mark > 49 and mark <= 59):
        print("E")
    else:
        print("F")

marks = input("Enter a grade: ")
allocateGrade(eval(marks))


Imagine you had to run the program above on a million records, it would definitely take a long time to execute. One trick you can you is to realise that not everyone is going to hit the top grade, so it would probably make sense to start the condition statements with F and working up to A.

Share your thoughts