The if-elif-else
statement in Python allows us to build programs that can make decisions based on certain conditions.
The if-elif-else
statement consists of:
if
statementelif
statementelse
statementThey combine to conditionally execute blocks of statements based on the logical expression.
If
statementThe if
statement executes a single block of statements based on a certain logical expression.
The syntax is given as:
if expression:
statement(s)
----
The expression
in the line of code above is usually a boolean expression (true or false). The program above will execute the statement provided only if the expression is true.
is_odd = Trueif is_odd:print("it's an odd number")print('They are not divisible by 2')
if-else
statementThe if-else
statement has two blocks of statements and executes them based on certain logical expressions.
The syntax is given as:
if expression:
statement_1(s)
---
else:
statement_2(s)
The code above will execute the if
block only if the expression
is true. If the expression
is false, then the program executes the statement_2
in the else
block.
is_odd = Falseif is_odd:print("it's an odd number")print('They are not divisible by 2')else:print("it's an even number")print('They are divisible by 2')
if-elif-else
statementThe elif
statement, short for else if
and in other words “otherwise if”, is added to the if-else
block when there are many more conditions. So basically, the if-elif-else
statement consists of several blocks.
The syntax is given as:
if expression:
statement_1(s)
---
elif expression_2:
statement_2(s)
---
else:
statement_3(s)
The code above will execute for just a block, only when it finds an expression
to be true.
is_odd = Falseis_prime = Trueif is_odd:print("it's an odd number")print('They are not divisible by 2')elif is_prime:print("it's a prime number")print("They only have two factors, itself and 1.")else:print("it's an even number")print('They are divisible by 2.')