Course 3.1Lesson 3 of 5
elif means else if. Python checks the conditions from the top, runs the lines of the first condition that is True and skips all the rest. else at the end catches everything that no condition caught. The order of the checks matters: put the most special condition first, because the first True one wins. A grade by marks and a ticket price by age are typical programs with an elif ladder.
Try the code and the simulations beside the lesson.
After this lesson you can
elif,True condition wins,A grade is not only pass or fail. It can be A, B, C or D. A ticket price depends on the age in several steps. For such a decision with many outcomes, you use elif, which means else if.
The picture shows a ladder of questions. Python starts at the top, and goes down one step at a time. The first condition that is True decides, and the rest of the ladder is skipped.
Because Python stops at the first True, the order of the checks matters. Look at this program, which has a mistake.
The rule for the order: put the most special (the hardest) condition first. For a grade, start with the highest marks. Then each elif only has to ask about its own step, because the higher ones have already been taken out.
The check for B does not need marks < 90. Python reaches it only when the check for A was False.
In the correct program, the second check is marks >= 75. It does not need to say marks >= 75 and marks < 90. Why? Because the first check already caught everything from 90 up. If we reach the second check, the marks must be less than 90. Each step uses what the earlier steps have already ruled out.
Another example. A ticket is free for children under 5, costs 50 rupees under 13, 100 rupees under 60, and 70 rupees for older people.
A common question is: when should I use elif, and when should I write a new if? Use elif when the choices exclude each other: exactly one of them is right. Use separate if statements when each condition is a separate question, and more than one can be true.
else if with two words. Python's word is elif.else. else has none.if where you need elif. Then two parts can run for the same value.< and <=. Always test the values at the edges.Start with two quick questions. Each New numbers gives you a fresh one, so you can practise as long as you like.
Then the labs and the problems:
elif means else if. Python stops at the first condition that is True.else at the end catches all that is left.elif can be short, because the earlier conditions have ruled things out.Try each one on your own first. If you are stuck, open a hint. Then check with Show the answer.
if, two elif and an else, how many parts run?marks >= 50 a bad first check for a grade ladder?if statements instead of elif?Every lesson is open to read. Enrolling also lets you:
Log in to join the discussion.
Loading…
This lesson is free to read. Enroll free to keep your place and take the tests.