Nested Conditionals

When building complex programs or algorithms there is a need for creating nested conditionals or conditional with multiple branches. The chained conditional example could also be solved using nested conditionals.
>>>if x == 0:
…      print ‘x is equal to 0’
…else:
…      if x < 0:
…           print ‘x is negative’
…     else: 
…           print ‘x is postive’
The outer conditional has two branches. The first branch contains a simple statement while second statement contains another if statement, which has two branches of its own. Those two branches are both simple statements, although they could have been conditional statements as well.
To test the result on previous example with nested conditionals write the following code.
 >>>value = raw_input(“Enter a value: “)
Enter a value: 0
>>>x = int(value)
>>>if x == 0:
…      print ‘x is equal to 0’
…else:
…      if x < 0:
…           print ‘x is negative’
…     else: 
…           print ‘x is postive’
…
x is equal to 0 

The general idea is to avoid nested conditionals as often as you can. The reason for this is that they become more difficult to read very quickly. To overcome a use of nested conditionals try to implement logical operators (and, or and not).
>>>x = 0
>>>if x <0 and x <10:
…      print ‘x is a positive single-digit number’
…else: 
…      print ‘x is equal to 0’ 
…
x is equal to 0 

Nema komentara:

Objavi komentar