If Elif Else - Lakelands Computing

Title
Go to content
If Elif Else
There are two reasons to use Elif (else if) in your if statements :

1) It lets you have more than two options, although you could do this with multiple Ifs and

2) If, elif, else is more efficient than if, if, if , else so your program will run faster

To understand why it is more efficient consider this:
The program has to run every single one of those if statements. It doesn't matter if the first one is true, making all the others impossible - the others would still run and be checked
  • If a > 90.... print ("top score")
  • If a > 80... print ("good result")
  • If a> 70..
  • If a> 60...
  • else.. print ("fail")
In this case the program checks the first if, seeing if the score is over 90. If it is it prints the statement but doesn't worry about the other checks. It only checks the 80 one if the 90 one is false. Then it only checks the 70 one if the 80 one is false as well. So it runs the minimum amount of code needed in each case.
  • If A > 90... print ("top score")
  • elif A > 80 .. print ("good")
  • elif A > 70 ...
  • elif A > 60
  • else .. print ("you failed")
All Text copyright Lakelands Academy & Mr T Purslow 2020.
All images copyright free / creative commons unless otherwise stated.
You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
All Text copyright Lakelands Academy & Mr T Purslow 2020.  All images copyright free / creative commons unless otherwise stated. You are welcome to use under a Creative Commons Attribution-nonCommercial-ShareAlike License.
Back to content