Tuesday, July 7, 2015

Python – Decision Making

In programming and scripting languages, conditional statements or conditional constructs are used to perform different computations or actions depending on whether a condition evaluates to true or false. 

The condition usually uses comparisons and arithmetic expressions with variables. These expressions are evaluated to the Boolean values True or False. The statements for the decision taking are called conditional statements. As most of us are pretty familiar with the decision making structures, I will make an walk on them and what python provides.

Python does provide 3 types of decision making as,


An if Statement consists of a Boolean expression followed by one or more statements. Below is an example of the standard if statement

>>> var = 100
>>> if (var == 100 ) : print "value us 100"
value us 100


An If-else statement can be followed by an optional else Statement which executes when the Boolean Expression is False. A snippet of how the If-else works is shown below.

>>> age = input("enter the age?")
enter the age?20
>>> if age<0:
...     print "age is Less than 0"
... elif age==10:
...     print "age is equal to 10"
... else:
...     print "age is Greater than 10"
age is Greater than 10

Nested – If

There may be cases where we need to perform a decision making that is based on other decision. Python provides the ability to do a nested-If while evaluating multiple decisions like

def hello(x,y,a,b):
    if x ==1:
        if y==2:
            print a
        print b


No comments :

Post a Comment