Explain Nested If-else in Python?

In real life, there are times when we must make decisions and then decide what to do next based on those decisions. Similar circumstances exist in programming, where we must make decisions and then execute the following block of code depending on those decisions. In programming languages, decision-making statements determine the course of programme execution. In Python, if else elif statement is used for decision making. In this session we will learn about nested if-else statement.

Syntax:

if test expression:
    Body of if
elif test expression:
    Body of elif
else: 
    Body of else

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. In this session the concept will be explained with the help of an example for a better understanding.

Example:


'''In this program, 
we check if the number is positive or
negative or zero and 
display an appropriate message'''

num = 3.4

Try these two variations as well:

# num = 0
# num = -4.5

if num > 0:
    print("Positive number")
elif num == 0:
    print("Zero")
else:
    print("Negative number")

When variable num is positive, Positive number is printed.
If num is equal to 0, Zero is printed.
If num is negative, Negative number is printed.