elif-Statement In Python

The elif Statement

The elif statement is used when the case that you want one thing to happen when a condition is true, and something else to happen when it is false. For that we have if else statement. The syntax looks like this:

General Syntax of it..else statement is

if TEST EXPRESSION:
	STATEMENTS_1  #executed if condition evaluates to True
else:
	STATEMENTS_2  #executed if condition evaluates to False

Each statement inside the if block of an if else statement is executed in order if the test expression evaluates to True.

The entire block of statements is skipped if the test expression evaluates to False, and instead all the statements under the else clause are executed.

Flowchart

There is no limit on the number of statements that can appear under the two clauses of an if else statement, but there has to be at least one statement in each block.

Occasionally, it is useful to have a section with no statements, for code you haven’t written yet. In that case, you can use the pass statement, which does nothing except act as a placeholder.

 if True: #This is always true
 	 pass #so this is always executed, but it does nohing
 else:
  	 pass

Example:

 age=21			#age=17
 if age >= 18:
     print("Eligible to vote")
 else:
     print("Not Eligible to vote")

Output:

 Eligible to vote

In the above example, when age is greater than 18, the test expression is true and body of if is executed and body of else is skipped.

If age is less than 18, the test expression is false and body of else is executed and body of if is skipped.

If age is equal to 18, the test expression is true and body of if is executed and body of else is skipped.

Read Also: