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.Â
The main difference between chained conditional and nested conditional is nesting. Chained conditional is a conditional that contains a series of alternative branches using if, elseif 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. The if, elseif and else statements in nested conditional have varying depths.
Example of chained conditional
grade= input("Enter your grade: ")
if grade=='A':
  print("You have an excellent grade")
elif grade=='B':
  print("You have a good grade")
elif grade=='C':
  print("You have a fair grade")
elif grade=='D':
  print("You have a poor grade")
elif grade=='E':
  print("You have failed")
else:
  print("You have entered an invalid grade")
Example of nested conditional
num=int(input("Enter a number: "))
if ​num==0:
   print(num, "is zero")
else:
   if num<0:
       print(num, "is negative")
   elif num>0:
       print(num, "is positive")
(2)The strategy for avoiding nesting condition is by use of logical operators such as ‘and’, ‘or’ and ‘not’.
Example of nested conditional
num=int(input("Enter a number: "))
if ​num>0:
   if num%2==0:
       print(num, "is a positive even number")
   else:
       print(num, "is a positive odd number")
elif num<0:
   if num%2==0:
       print(num," is a negative even number")
   else:
       print(num, "is a negative odd number")
else:
   print(num, "is zero")
Equivalent single conditional
num=int(input("Enter a number: "))
if ​num>0 and num%2==0:
   print(num, "is a positive even number")
elif ​num>0 and num%2 !=0:
   print(num, "is a positive odd number")
elif ​num<0 and num%2==0:
   print(num, "is a negative even number")
elif ​num<0 and num%2 !=0:
   print(num, "is a negative odd number")
else:
   print(num," is zero")
Comments
Leave a comment