INTRODUCTION TO PROGRAMMING WITH PYTHON (2015)

CHAPTER 6. CONDITIONALS, FLOW CONTROL, DECISIONS

Useful programs are able to make decisions based on the inputs. This is achieved by giving them the ability to change the behavior or flow of the program based on the inputs. This is done using conditional statements.

The flow of the code is the order of the code you have written. Recall the birthday example. You may have planned that the hallway lights will go up first, followed by the friends on the stairways singing the songs, someone coming with the cake, etc. 

But different inputs (or reactions by your friends) the flow of the party might have to change.

In coding, normally, when the code is executed, the interpreter reads it line by line, moving from the top to the bottom. However, at times you may need to execute a function that begins 40 lines ahead. The most effective way of increasing efficiency of the program is to break the flow and immediately bring the interpreter to the function and execute it.

When there is a need to break the code and execute a different block of code altogether to complete a task, conditionals come in.

Conditionals can be divided into basic conditions and the If conditions, including:

·               If-Statement

·               If-Else Statement

Let’s take them one by one.

BASIC CONDITIONS

These include all the arithmetic comparisons, such as less than (<), greater than (>), equal (=). For example:

3<4

3>2

t=5

t>7

All of the above have Boolean results i.e. they are either true or false. These conditions can be used to control the flow of the program using conditional statements.

However, not all arithmetic decision are transferred exactly to Python:

Greater than

Less than

Greater than or equal

>=

Less than or equal

<=

Equals

=

==

Not equal

!=

CONTROL FLOW WITH THE IF-STATEMENT

We are writing a code for a moving company that offers flat rates for all items less than 60kg, whereas anything greater than that is charged $20 extra. Our code will used with their weighing machine to inform the customer of the extra charges. Here’s an example code:

weight = float (input (“Please enter the weight of your luggage (in Kg):”))

if weight > 60:

print (“This exceeds our 60 Kg flat-rate limit. An additional $20 is applied for heavier luggage like this.”)

print (“Thank you for your business.”)

Notice the indentation before the firstprint command. This indentation tells Python what to do when the statement weigh > 60 is true or false:

·               When the weight is greater than 60 kg, it prints additional charges, and

·               When it is not true (weight<60), it thanks the customer.

The syntax for the if-statement is:

if condition:

              Indented code/statement

# the colon is part of the syntax.

What if you want to execute separate codes for both, True and False conditions? If-else statement is used for that as well using the if-else statement.

CONTROL FLOW WITH IF-ELSE STATEMENT

The general syntax for if-else statements in Python is:

if condition:

              Indented code if condition is True

else:

              Indented code if condition is False

The indented blocks can have any number of further statements inside them. For example:

time = float (input (‘How long did you run?’))

if time > 20:

              print (‘ Good work! Let’s continue maintaining our health’)

else:

              print (‘Good effort. Let’s try to hit our target tomorrow!’)

print (‘Exercise for Healthy Living’)

The if-else statement is limited to testing a single condition and control the flow using only two results (True/False). Multiple tests can be included using theif-elifstatement.

CONTROLLING FLOW USING IF-ELIF STATEMENTS

Why not use the if-else statement repeatedly in case of multiple tests? Let’s take the example of grade assigner:

def GradeAssign (score):

    if score >= 85:

        assign = 'A'

    else:   # if not A then maybe B, C, D or F?

        if score >= 75:

            assign = 'B'

        else:  # if not A then maybe C, D or F?

            if score >= 65:

                assign = 'C'

            else:    # grade must D or F

                if score >= 60:

                    assign = 'D'

                else:

                    assign = 'F'

    return assign

Notice the number of indentations.

As your code grows longer, this will become problematic. See how if-elif transforms it:

def GradeAssign(score):

    if score >= 85:

        letter = 'A'

    elif score >= 75:

        letter = 'B'

    elif score >= 65:

        letter = 'C'

    elif score >= 60:

        letter = 'D'

    else:

        letter = 'F'

    return letter

NESTED STATEMENTS

Your code can have statements within statements as well:

if t>60:

              Indented statement #1

else:

if t<30:             

              Another indented statement #2

else:

              Indented statement # 3

As your program grows, nesting statements will increase the decision-making ability of your code.