Python Code Example: multi-branches

In Python there are also multiple branches represented by the elif statement

The if-conditions are evaluated in sequence until one of them is true. Then finally the code section belonging to this condition is executed and the multiple branching handling is finished. The else-part is only executed if none of the conditions is true.

Code Example

firstNumber = input("Please enter first number: ")
secondNumber = input("Please enter second number: ")

if (firstNumber > secondNumber):
    print(firstNumber + " > " + secondNumber)
elif (firstNumber < secondNumber):
    print(firstNumber + " < " + secondNumber)
else:
    print(firstNumber + " = " + secondNumber)
Output
Please enter first number: 5
Please enter second number: 8
5 < 8
Code Explanation

It’s a code that prompts the user to input two numbers, then it compares the two numbers and outputs the result as a string comparing the two numbers. If the first number is greater than the second number, it outputs a string saying “firstNumber > secondNumber”, if the first number is smaller than the second number it outputs a string saying “firstNumber < secondNumber”, and if the two numbers are equal, it outputs a string saying “firstNumber = secondNumber”.