CH2 If Else
CH2 If Else
else Statement
if test expression:
statement(s)
Here, the program evaluates the test expression and will execute statement(s) only if the te
expression is True .
In Python, the body of the if statement is indicated by the indentation. The body starts witt
indentation and the first unindented line marks the end.
Python interprets non-zero values as True . None and 0 are interpreted as False .
Test False
Expression
True
Body of if
num = 3
if num > 0 :
print ( num, " is a positive number " ) .
print ( " This is always printed " ).
num = -1
if num > 0:
print ( num, " is a positive number " ) .
print ( " This is also always printed " ).
Run Code
3 is a positive number
This is always printed
This is also always printed .
When the variable num is equal to 3, test expression is true and statements inside the body
if are executed.
If the variable [ num | is equal to -1, test expression is false and statements inside the body of
The printQ statement falls outside of the [if] block (unindented). Hence, it is executed
regardless of the test expression.
if test expression:
Body of if
else:
Body of else
The if..else statement evaluates test expression and will execute the body of if onlywl
the test condition is True .
If the condition is False , the body of else is executed. Indentation is used to separate the
blocks.
Example of if...else
# Program checks if the number is positive or negative
# And displays an appropriate message
num = 3
if num > = 0 :
print ( " Positive or Zero " )
else :
print ( " Negative number " )
Run Code
Output
Positive or Zero
In the above example, when [W| is equal to 3, the test expression is true and the body of [l
is executed and the [ body ] of else is skipped.
If num is equal to -5, the test expression is false and the body of else is executed and the
body of fi?) is skipped.
If num is equal to 0, the test expression is true and body of |TF| is executed and body of els
skipped.
if test expression:
Body of if
elif test expression:
Body of elif
else:
Body of else
[
The elif is short for else if. It allows us to check for multiple expressions.
If the condition for (T?) is False], it checks the condition of the next elif block and so on.
Only one block among the several if...elif...else blocks is executed according to the
condition.
The (Tf) block can have only one|eise|block. But it can have multiple [ elif ] blocks.
Flowchart of if...elif...else
,
Test False
S' Expression
of if
True
Test False
Expression
Body of if | of elif
rue
i
Fig: Operation of if ...elif... pise statement
num = 3.4
if num > 0 :
print ( " Positive number " )
elif num == 0 :
print ( " Zero " )
else :
print ( " Negative number " )
Run Code
Run Code
Output 1
Enter a number : 5
Positive number
Output 2
Enter a number : -1
Negative number
Enter a number: 0
Zero