Home > Blockchain >  In python, can a conditional statement be called both nested and chained?
In python, can a conditional statement be called both nested and chained?

Time:06-04

I am taking online classes on Udemy and the course suggests that a conditional statement cannot be both chained nested at the same time.

I looked it up on google and found this:

Chained conditional is a conditional that contains a series of alternative branches using if, elif and else statements that are all indented at the same depth. There is no nesting in chained conditional. On the other hand, nested conditional is where one conditional is nested within another conditional.

https://www.assignmentexpert.com/homework-answers/programming-and-computer-science/python/question-184682*

Now here is an example which confuses me.

answer = None
x = randn()
if x >= 1:
  answer = "x is greater than 1"
elif x >= -1:
  answer = "x is between -1 and 1"
else:
  if x >=-2:
    answer = "x is between -2 and -1"
  else:
    answer = "x is less than -2"
print(x)
print(answer)

There are nested conditions within a chained conditional. So shouldn't this be called both chained and nested?

CodePudding user response:

Based on the example and definitions given, it is possible to have nesting in chained conditional statements (aka the code will run), but the question is should you nest in a chain?

Maybe the course suggests that a conditional statement cannot be both chained and nested at the same time because you'd be able to rewrite the code so that the nested conditional statements are added to the chain instead, which will produce cleaner and more readable code.

For example, the code you gave can easily be rewritten as follows:

answer = None
x = randn()
if x >= 1:
  answer = "x is greater than 1"
elif x >= -1:
  answer = "x is between -1 and 1"

# change happens below
elif x >=-2:
  answer = "x is between -2 and -1"
else:
  answer = "x is less than -2"
print(x)
print(answer)

TDLR: In terms of execution, the code will run without errors. But in terms of design and readability, it's bad and thus, not good practice and not advisable to do.

  • Related