Chained Conditionals

Sometimes there is need for more than two possibilities and we need multiple branches. The solution to this problem is to create chained conditional. The structure of chained conditional is given below.
>>>if x > 0:
…      print ‘x is positive’
… elif x < 0:
…     print ‘x is negative’
…else:
…     print ‘x is equal to 0’
The ‘elif’ is short form ‘else if’.
To test the previous code here is an example.
>>>value = raw_input(“Enter a value: “)
Enter a value: 0
>>>x = int(value)
>>>if x > 0: 
…      print ‘x is positive’ 
… elif x < 0:
…     print ‘x is negative’
…else: 
…     print ‘x is equal to 0’ 
x is equal to 0 

Nema komentara:

Objavi komentar