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.
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")
Comments
Leave a comment