4 Key Facts About Nested Statements in Python

Nested Statements in Python

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).

Nesting conditionals like this is powerful, but it carries a practical cost that’s worth flagging early. Most experienced programmers keep nested conditionals to no more than two or three levels deep, since every additional layer of indentation makes the logic measurably harder to read, trace, and debug – the same tangled-logic problem that once plagued unstructured programs written with goto, recreated here one level of indentation at a time instead of one jump at a time. When a block of logic threatens to nest more deeply than that, the usual fix isn’t to keep nesting further but to restructure it. A guard clause – checking for the conditions that should exit a function early, right at the top, before the main logic even begins – is one of the simplest ways to flatten what would otherwise turn into a pyramid of nested ifs. Pulling a deeply nested condition out into its own clearly named function is another option: instead of testing four raw conditions inline, as the example above does, a function like is_a_cat(phylum, class_, order, family) hides the nesting inside a single, readable call. Neither technique changes what the code actually does; both exist purely to keep the logic legible to the next person who has to read it – which, a few months later, is often you.

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

No Comments

Leave a Reply

Recent Comments

No comments to show.