Describe the difference between a chained conditional and a nested conditional. Give an example of each.
Deeply nested conditionals can become difficult to read. Describe a strategy for avoiding nested conditionals. Give a example of a nested conditional that can be modified to become a single conditional, and show the equivalent single conditional.
Q237956
var =1000.
If var > 3000:
print "Expression value is colossal"
if var<1000:
print "Expression value not found"
elif number==2999:
print "Expression value not accurate"
elif number==2001"
print "Expression value found"
else:
print "Expression value error"
A chained conditional is an alternative way of writing a nested conditional in a shorter expression of the same command.
For example:
var=100
If var<100:
print ("Value not found")
elif var==100:
print ("Value found")
else var >100:
print ("Error")
One way of voiding nested conditions is by using the filter function in your expressions, therefore reducing the code into two or one line of command.
For example, the nested code is as follows;
var= 1, 2, 3, 4, 5, 6, 7, 8, 9, 16 , 25
if var==1, 3, 5, 7:
print "Odd numbers"
elif var==4,9,16,25:
print "square numbers"
else: print "Irrelevant"
When the filter function is used, the code is reduced into the following:
var=1, 2, 3, 4, 5, 6, 7, 8, 9, 16 , 25
odd numbers==filter(lambda x: x%2!=0,var
print(list(odd numbers))
square numbers==filter(lambda x: x2!=0, var
print(list(square numbers))
Comments
Leave a comment