DECISION MAKING

Decision Making:

Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions.

Decision structures evaluate multiple expressions which produce TRUE or FALSE as outcome. You need to determine which action to take and which statements to execute if outcome is TRUE or FALSE otherwise.

Following is the general form of a typical decision making structure found in most of the programming languages –

Python programming language assumes any non-zero and non-null values as TRUE, and if it is either zero or null, then it is assumed as FALSE value.

Python programming language provides following types of decision making statements. Click the following links to check their detail.

Sr.No.

Statement & Description

1

if statements

An if statement consists of a boolean expression followed by one or more statements.

2

if...else statements

An if statement can be followed by an optional else statement, which executes when the boolean expression is FALSE.

3

nested if statements

You can use one if or else if statement inside another if or else if statement(s).

 

IF STATEMENT:

If the suite of an if clause consists only of a single line, it may go on the same line as the header statement.

Here is an example of a one-line if clause −

Live Demo

var = 100

if ( var == 100 ) : print "Value of expression is 100"

print "Good bye!"

When the above code is executed, it produces the following result −

Value of expression is 100

Good bye!

 

If, Elif, and Else:

In Python you can define a series of conditionals using if for the first one, elif for the rest, up until the final

(optional) else for anything not caught by the other conditionals.

number = 5

if number > 2:

    print("Number is bigger than 2.")

elif number < 2:  # Optional clause (you can have multiple elifs)

    print("Number is smaller than 2.")

else:  # Optional clause (you can only have one else)

    print("Number is 2.")

 

 

Outputs Number is bigger than 2

Using else if instead of elif will trigger a syntax error and is not allowed.

 

NESTED IF:

We can have a if...elif...else statement inside another if...elif...else statement. This is called nesting in computer programming.

Any number of these statements can be nested inside one another. Indentation is the only way to figure out the level of nesting. They can get confusing, so they must be avoided unless necessary.

Python Nested if Example

'''In this program, we input a number

check if the number is positive or
negative or zero and display
an appropriate message
This time we use nested if statement'''
 
num = float(input("Enter a number: "))
if num >= 0:
    if num == 0:
        print("Zero")
    else:
        print("Positive number")
else:
    print("Negative number")

 

Output 1

Enter a number: 5
Positive number

Output 2

Enter a number: -1
Negative number

Output 3

Enter a number: 0
Zero

 


Comments