Search

Python Decision Control Structures: The Python if else Statement - Part 1

 

decision making in programming in python

We all need to make decisions. We decide on what to eat, what to wear, what to learn, or where to work. Computers also make decisions; at least, the decisions we code. You designate what decision you want a program to make using control structures in your code.

A control structure is a block of programming that analyses one or more variables and then decides on what to do next based on the parameters given by the variables. Another word for control structures is flow of control. Given conditions and parameters, this is the decision making construct in any program.

There are three types of control structures or control flow. They are the sequential, the selection, and repetition control structures.

  1. Sequential control Flow
  2. This is when you execute statements one after the other in the order they appear in the program. Provided there are no syntax or semantic errors, the statement will run from the first to the last statement.

    Here is the flow chart for the sequential control flow. 

    python sequential control flow chart
     

  3. Selection Control Flow
  4. This involves choosing between two or more alternative paths, based on the evaluation of the conditional statement.

    Here is a typical flowchart. 

    python if else statement control flowchart
     

    Selection control flows are usually implemented as python conditional statements and could be a python if statement, python if else statement, or python if elif else statement.

  5. Repetition control flow
  6. This involves repeating a series of statements several times based on the evaluation of a conditional statement.

    Here is a typical flowchart. 

    python while and for loop flowchart
     

    Repetition control, or sometimes called iteration control, flows are usually implemented in python using the while and for loops.

Apart from the sequential control flow, the selection control flow which makes use of conditional and the repetition control flow which makes use of loops all consist of a condition to be evaluated and a body of statements. You use the python syntax for defining blocks of code to help python interpret your statements appropriately. This involves using the colon character to delimit the beginning of a block of code that acts as the body for a control structure. If the body is just a one-line statement, you can place it on the same line with the condition being evaluated and just after the colon. Or you could decide to place it on a separate line. But if the body is more than one line, you use python’s principles of indentation to place it on a separate line after the colon. Using indented blocks to designate the body helps python to interpret the code as a group of statements belonging to the same control flow. You should already be familiar with python’s principle of indentation. But let me just give some examples with a python while loop.


# using a while loop to show block indentation
while n < 5:  #use colon to show block of code comes next
    # indent the block of code in body by 4 spaces
    print(n)
    n += 1

In any program, you could end up using one, two or all of the control flows. In this post, we will discuss about the selection control flow, while in the next part we will discuss the repetition control flow.

Python implements the selection control flow using conditionals.

Conditonal statements.

Conditional statements in python, also known as the python if statement, if else statement, or if elif else statement, are a way for one to execute a chosen block of code based on the run-time evaluation of one or more Boolean expressions. You usually write the conditional or python if statement in the following way:


if first_condition:
    first_body
elif second_condition:
    second_body
elif third_condition:
    third_body
else:
    fourth_body

Each condition is a Boolean expression that evaluates to True or False, and each body consists of one or more statements that are executed conditionally. On the success of the first condition, the body is executed and no other condition is evaluated after that. But if it fails, the next condition is evaluated for whether it will succeed or fail. When any condition succeeds, all other conditions are discarded and only the body of the condition that succeeds is executed. If none of the conditions succeed, the else body is executed. Note that precisely only the body following a successful conditional will be executed, and sometimes none at all if there is no else statement.

In the example code above, I used two elif statements. You can use any number of elif statements, including zero.

Note that when you want to evaluate a conditional in the if statement, you are evaluating it based on whether it resolves to True or False. In some cases, if you are not evaluating the Boolean expression based on a specific value but on whether the variable has value, you don’t need to evaluate for True or False because every variable is already True when it has a value. You only write out the variable name.

For example, don’t do this:


if fruits == 'True':
    print('Fruits variable has a value')                

Rather you produce more optimized code if you write it like this, omitting the test for True:


#I removed the test for True
if fruits: 
    print('Fruits variable has a value')                

The elif and else statements in conditional constructs are optional. Let’s illustrate all with examples.

  1. Where only the python if statement is used.
  2. 
    if hungry:
        eat_food()
    
  3. Where the python if else statements are used.
  4. Some call this the python if then else statement which is a correspondence to other programming languages like java.

    
    if hungry:
        eat_food()
    else:
        sleep()
    
  5. Where only the python if elif statements are used.
  6. 
    if hungry:
        eat_food()
    elif tired:
        rest()
    
  7. Where all three statements, if elif else statements, are used.
  8. This looks like a case switch statement in python; a throwback from java.

     
    if hungry:
        eat_food()
    elif tired:
        rest()
    elif bored:
        watch_tv()
    else:
        sleep()
    

So I have outlined four different ways the conditional construct can be used. Note that only the if statement is required; the others are optional.

One other thing I need you to know about the block indentation so you don’t run into problems. When you have code you want to specify that is not included in the body of the conditional construct, you need to take back your indentation by 4 steps. For example, if after the else block below I want my program to shift control to another activity which does not lie in the conditional construct, i.e do_next_activity(), my indentation goes back 4 steps.


if hungry:
    eat_food()
else:
    sleep()
# this is not part of the conditional construct
# it goes back 4 steps in indentation    
do_next_activity() 

From above, do_next_acitivity() goes back 4 steps and is not part of the indentation for the conditional constructs. It does not participate in the indentation.

Lastly, we have python nested if statements.

Python nested if statements.

We may nest one control structure within another, and to do this successfully, we rely on the indentation to make our intent clear to python. Let’s take our if statement a bit further and nest it.


if hungry:
    if food_exists:
        cook_food()
    else:
        buy_food()
    eat_food()
do_next_activity()                                   

You can now see that we have a nested if statement within another if statement. All you need to do is to be careful about making sure your indentation is correct.

We can illustrate the nested conditional construct above with a traditional flowchart. That makes for easy understanding.

python decision making flowchart

In the next post, I will discuss on the repetition control flow which consists of the while and for loops.

No comments:

Post a Comment

Your comments here!

Matched content