Answer to Question #238657 in Python for Ashkan

Question #238657

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.


1
Expert's answer
2021-09-18T02:57:37-0400

The best strategy for avoiding nested

conditionals is to use logical operators like: and,

or, not.


cond1 = True
cond2 = True


# chained
if cond1:
    print("Cond1 is true")
elif cond2:
    print("Cond2 is true, but cond1 is false")
else:
    print("Both true")
    


# nested
if cond1:
    if cond2:
        print("Cond1 is true and cond2 is true")
    else:
        print("Cond1 is true, but cond2 is false")
else:
    print("Cond1 is false, but cond2 is true or false")
    


# example
if cond1:
    if cond2:
        print("Cond1 is true and cond2 is true")
# removed the nesting        
if cond1 and cond2:
        print("Cond1 is true and cond2 is true")

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS