Chained Conditionals (if elif else)

Chained Conditional can be used when we need more than two branches.

Syntax

if boolean expression:
statement 1
statement 2
statement n
elif boolean expression:
statement 1
..
statement n
else:
statement 1
statement n
  • There is no limit on the number of elif statements. If there is an else clause, it has to be at the end, but there doesn’t have to be one.

  • Each condition is checked in order. If the first is false, the next is checked, and so on. If one of them is true, the corresponding branch runs and the statement ends. Even if more than one condition is true, only the first true branch runs.

Example

x=int(input())
y=int(input())
if x < y:
print('x is less than y')
elif x > y:
print('x is greater than y')
else:
print('x and y are equal')
Input:
5
10
Output:
x is less than y

References

  • Allen B. Downey, “Think Python: How to Think Like a Computer Scientist‘‘, 2nd edition, Updated for Python 3, Shroff/O‘Reilly Publishers, 2016 (http://greenteapress.com/wp/thinkpython/)
  • Guido van Rossum and Fred L. Drake Jr, ―An Introduction to Python – Revised and updated for Python 3.2, Network Theory Ltd., 2011.
  • John V Guttag, ―Introduction to Computation and Programming Using Python‘‘, Revised and expanded Edition, MIT Press , 2013
  • Robert Sedgewick, Kevin Wayne, Robert Dondero, ―Introduction to Programming in Python: An Inter-disciplinary Approach, Pearson India Education Services Pvt. Ltd., 2016.
  • Timothy A. Budd, ―Exploring Python‖, Mc-Graw Hill Education (India) Private Ltd.,, 2015. 4. Kenneth A. Lambert, ―Fundamentals of Python: First Programs‖, CENGAGE Learning, 2012.
  • Charles Dierbach, ―Introduction to Computer Science using Python: A Computational Problem-Solving Focus, Wiley India Edition, 2013.
  • Paul Gries, Jennifer Campbell and Jason Montojo, ―Practical Programming: An Introduction to Computer Science using Python 3‖, Second edition, Pragmatic Programmers, LLC, 2013.