Answer to Question #237956 in Python for Joel

Question #237956

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. 



1
Expert's answer
2021-09-17T02:04:30-0400

Q237956

  1. A nested conditional describes a statement where an 'if' or 'else if' condition is used inside another 'if' or 'else if' statement. Basically, a condition(s) is nested between two other conditions. For example:

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))


 



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