Python Chapter#4: If-else

Ankur Kulhari

In Python:

  • Any non-zero and non-null values are considered as TRUE, and
  • Zero or NULL are considered as FALSE value

Python has 3 types of decision/if-else statements as:

Statement Description Syntax
if An if statement consists of a boolean expression followed by one or more statements.
Ex:Boolean expression: (x>y)
if expression:
   statement(s)
if…else An if statement can be followed by an optional else statement, which executes when the boolean expression (if condition) is FALSE.
if expression:
   statement(s)
else:
   statement(s)
nested if if or else if statement can be used inside another if or else if statement(s).
if expression1:
   statement(s)
   if expression2:
      statement(s)
   elif expression3:
      statement(s)
   else:
      statement(s)
else:
   statement(s)

Ex (nested if-else):
x = 12
if x < 20:
   print "Expression value is < 20"
   if x == 14:
      print "and = 14"
   elif x == 12:
      print "and = 12"
   elif x == 10:
      print "and = 10"
elif x < 10:
   print "Expression value is < 10"
else:
   print "True expression not found"
print "Tata!"

OUTPUT:

Expression value is < 20
and = 12
Tata!

What do you think about the article?