How to perform branching to control logic flow in python programming language using if statement

Posted on

Introduction

Actually, in almost programming language in general, there is a feature or concept for controlling the logic flow of the execution of process. That feature or concept is the branching process where the control of the logic flow of the execution of the process can be define. The feature or concept of branching process is actually exist when there are several alternative flows that can happen upon the execution of that process. By using the branching process feature or concept, just set the logic of the execution in order to control the flow of the process.

In python programming language, branching process feature or concept is available using several syntaks. One of the syntax is the usage of the if statement.

Branching Example using If Statement

So, branching process the execution of the process is possible by fulfilling the condition where it exist in the definition in the if statement. The following are the syntaks for the branching process :

score = 85

if score >= 60 :
   print("Congratulations your pass the exam")

if score < 60 :
   print("Sorry, you fail the exam")

The output of the above command exist as follows :

[user@host python]# python3 if-statement.py
Congratulations your pass the exam
[user@host python]#

The execution of the python script above obviously start from the top to the bottom of the line of codes. But at a certain line, there is a branching of the process where the execution of it depends on a certain condition or circumstance. There are two simple branches process where the process is just printing an information. The printed information depend on the value of the variable with the name of score. If that variable pass the condition defined in the branch process statement, it will then route the flow of the process to execute the inner line of code inside the branch process block.

Since the above variable’s value is 85, it only meet the condition or the requirement defined in only one branch process. It is the first block of the branch process where the score is actually greater than 60. Since it met the requirement, it will then print the line of code inside that first branch process block. It will then continue on to be inspected by the second branch process according to the condition defined. Since it does not meet the requirement exist in the condition defined, the process will just flow to the end without having to execute the line of code inside the second branch process block.

Leave a Reply