Python Code Example: nested if-else statement

When an if-else statement is executed in the body of another if-else statement, it is called nested.

Code Example

number = 56

if (number <= 100):
    if (number < 50):
        print("Value is smaller than 50")
    elif (number == 50):
        print("Value is 50")
    else:
        print("Value is between 51 und 100")
else:
    print("Value is greater than 100")
Output
Value is between 51 und 100
Code Explanation

The code compares the value of the variable number against several conditions to determine what to print.

  • If the value of number is less than or equal to 100, it enters the second set of conditionals:
    • If the value of number is less than 50, it prints “Value is smaller than 50”.
    • If the value of number is equal to 50, it prints “Value is 50”.
    • If neither of the previous conditions are met, it prints “Value is between 51 and 100”.
  • If the value of number is greater than 100, it prints “Value is greater than 100”.

In this example, number is 56, so it will print “Value is between 51 and 100”.