Friday 29 June 2018

Python nested if statement

Python nested-if statement

Nested if statements in any programming language means an if statement inside another if statement. Python also allows us to nest if statements within if statements. i.e, we can write an if statement inside another if statement.

Syntax of nested-if statement:

if (condition 1):
   # Code to be executed when condition 1 is true
   if (condition 2):
      # Code to be executed when condition 2 is true
   # end of inner if Block
# end of outer if Block

Example of Python nested if statement

# Python program to demonstrate nested-if statement
# Program will check whether entered number is positive or negative or zero.

number = int(input("Enter a number: "))
if number >= 0:
    if number == 0:
        print("It's Zero")
    else:
        print("It's Positive number")
else:
    print("It's Negative number")

Output of program

Enter a number: 5
It's Positive number

if-elif-else ladder

The if statements are executed from the top to the bottom sequentially. When one of the conditions controlling the if is true, the statement associated with that if is executed, and the rest of the ladder is bypassed. If none of the conditions is true, then the last else statement written will be executed.

Syntax of if-elif-else

if (condition 1):
    statements for condition 1
elif (condition 2):
    statements for condition 2
.
.
else:
    statements for else

Example of Python if-elif-else ladder

number = int(input("Enter number in range of 1 to 5:"))
if (number == 1):
print ("It’s One")
elif (number == 2):
print ("It’s Two")
elif (number == 3):
print ("It’s Three")
elif (number == 4):
print ("It’s Four")
elif (number == 5):
print ("It’s Five")
else:
print ("It’s not in range of 1 to 5")

Output of program

Enter number in range of 1 to 5:3
It’s Three

* * * * *

<  Back to Home Page >



No comments:

Post a Comment