It is possible to nest multiple conditional statements within each other to perform complex decision-making. These statements are 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")
embranchement == "vertebrates", class_== "mammals", order == "carnivores", and family == "felids") are true.embranchement == "vertebrates" and class_ == "mammals").if ordr_ == "carnivores" and will only execute if the first two conditions are true.embranchement is “vertebrates” and class_ is “birds”.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