Start a Project

It is possible to nest multiple conditional statements within each other to perform complex decision-making. These statements are nested statements in python.

Example of nested statements in python:

phylum = "vertebrates"
class_ = "mammals"
order = "carnivores"
family = "felids"

if phylum == "vertebrates":
    if class_ == "mammals":
        if order == "carnivores":
            if family == "felids":
                print("This might be a cat")
        print("It's certainly a mammal")
    elif class_ == "birds":
        print("This might be a canary")

print("Animal classification is complex")

Analysis of this Example

  • The phrase “This might be a cat” (line 5) will only be displayed if all four conditions (embranchement == "vertebrates", class_== "mammals", order == "carnivores", and family == "felids") are true.
  • The phrase “It’s certainly a mammal” (line 6) will be displayed if the first two conditions are met (embranchement == "vertebrates" and class_ == "mammals").
  • Since line 6 is indented at the same level as line 3, it belongs to the same block as if ordr_ == "carnivores" and will only execute if the first two conditions are true.
  • The phrase “This might be a canary” (line 8) will be displayed if embranchement is “vertebrates” and class_ is “birds”.
  • The phrase “Animal classification is complex” (line 9) will always be displayed in all cases, because it is not indented under any if condition—it is part of the main program block (starting from line 1).

In the next article, we we read about while loop in Python.

Leave a Comment

Your email address will not be published. Required fields are marked *