if...else if...else Statement


if...else if...else Statement

The if-else statement enables us to check multiple conditions and execute the specific block of code, depending on which condition the blocks hold. The if-else statement works like an if-else-if ladder code, allowing other conditions to be accommodated in the code other than the if block. If all of the above conditions are False, then statements of else are executed.

Syntax:

if < test expression>:
< STATEMENT>
elif < test expression>:
< STATEMENT>
else:
< STATEMENT>

The if-else statement can be used in python for decision-making.
The statement else can be combined with the if statement. The statement else has the block of code that runs if the conditional expression in an if statement goes false or 0.
The condition if-else combines an additional mark in the decision-making process as compared to the single if statement.
The if-else statement is conditional. Decision-making is needed if we want to run a code only when a specific condition is fulfilled

  • If we want to run only one statement, we can use if for one and else for the other and put it all in the same line.
  • If-else appraises test expression, and 'if' will run the code if only when the given condition is satisfied, else the code will be skipped.
  • If the given condition is not satisfied, then code of else will be executed.
  • The statement else is optional, and there should be at most only one else statement following if.

Example:

a = 33 b = 33 if b > a: print("Knowledge2life 1") elif a == b: print("Knowledge2life 2") else: print("Knowledge2life 3")

OUTPUT:

Knowledge2life 2