Describe the difference between a chained conditional and a nested conditional. Give your own example of each. Do not copy examples from the textbook.
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. Do not copy the example from the textbook.
A chained conditional is when you use if/elif/else flow controls and they are all dedicated to the same depth of the function. No nesting in this case.
def fruit_color(fruit):
if fruit == 'apple':
print('red')
elif fruit == 'banana':
print('yellow')
else fruit == 'pear':
print('green')
A nested conditional is when you use if/elif/else flow controls and the conditionals may locate on different depth to create a more nuanced sequence of conditionals.
if a < b:
print("a is less than b")
else:
if a > b:
print("a is greater than b")
else:
print("a and b must be equal")
Nesting is the key differentiator between a chained conditional and a nested conditional. When considering different ways of the function definition, some conditions may be combined or contracted to a simpler representation
def list_lenght(list1, list2):
if len(list1) == 8:
if len(list2) == 8:
print(f"{list1} is equal in size to {list2}")
else:
print(f"{list1} isn't equal in size to {list2}")
else:
print('They have different length!')
def list_lenght2(list1, list2):
if len(list1) == 8 and len(list2) == 8:
print(f"{list1} is equal in size to {list2}")
else:
print(f"{list1} isn't equal in size to {list2}")
Comments
Leave a comment