Decision Making in Python

By Decision making is the list of conditions occurring during the execution of the program and specifying the actions taken according to the conditions.
It produces TRUE or FALSE as the outcome.
If statement is called as decision making statement.

If Statement

The if statement executes some statements only if some condition holds, or choose statements to execute depending on several mutually exclusive conditions.

There are four type of decision making if statement in python,

1) Simple if

The if statement is used to take a decision based on the condition.
If the condition is satisfied, the statement of true block is executed, otherwise it is moved out.

Syntax

if(condition):
statement

NOTE :
– Must add : after the end of the condition
– Must put 4 space inside the condition, write any statement.

Example :

num = 4
if num > 0:
print(num, " is a positive number.")

OUTPUT

4 is a positive number.

2) if…else Statement

In if…else condition, if the condition is true, it will execute the true block;
Otherwise it will execute the false block.

Syntax

if test expression:
body of if
else:
body of else

Example :

num = 4
if num > 0:
print(num, "is Greater then Zero")
else:
print(num, "is Less then Zero")

OUTPUT

4 is Greater then Zero.

3) if…elif…else Statement

The elif is the short form of else if.
It is used to check for multiple expression.
If the condition is False, it moves to the condition of the next elif block. If whole conditions are False, body of the the else is executed.
Only one block, along with several if…elif…else blocks, are executed according to the state.
The “if” block can contain only one “else” block. But it can hava many “elif” blocks.

Syntax

if test expression:
body of if
elif test expression:
body of elif
else:
body of else

num = -4
if num > 0:
print(num, "is Greater then Zero")
elif num < 0:
print(num, "is Less then Zero")
else:
print(num, "is Zero")

OUTPUT

-4 is Less then Zero.

4) Nested if Statement

In a nested if construct, you can have an if…elif…else construct inside another if…elif…else construct.

Syntax

if test expression:
if test expression:
body of if
else:
body of else
else:
body of else

num =  float(input("Enter a number:"))
if num >= 0:
if num == 0:
print("Zero")
else:
print("Greater than Zero")
else:
print("Less than Zero")

OUTPUT

Enter a number:0
Zero

Next we discuss about looping structure in python.

« Previous | Next »

1 Comment
1. […] « Previous […]

Latest Blog

What is New in Android studio 3.5

Android studio 3.5 include some of the new features and behavioures changes. like, Memory Management Setting, Memory usage report,...

Application Of Various Operation Research Techniques

Application Of Various Operation Research Techniques are, Linear programming, Decision theory, Simulation, Inventory control, Network techniques and CPM