Question #99682

Describe the difference between a chained conditional and a nested conditional. Give your own example of each.


Deeply nested conditionals can become difficult to read. Describe a strategy for avoiding nested conditionals. Give your own example of a nested conditional that can be modified to become a single conditional, and show the equivalent single conditional.

Expert's answer

# i'ts nested conditional using if afte else: and creates more code
x = 0
if x < 0:
    print("This number ",  x, " is negative.")
else:
    if x > 0:
        print(x, " is positive")
    else:
        print(x, " is 0")

#it's chained conditoinal using elif and return sample result and creates less code
if x < 0:
    print("This number ",  x, " is negative.")
elif (x > 0):
    print(x, " is positive")
else:
    print(x, " is 0")
# If you need that constructions [else: if()] you can replace it with elif
LATEST TUTORIALS
APPROVED BY CLIENTS