Using ELSE IF to provide more choices
In programmingThe process of writing computer software., selectionA decision within a computer program when the program decides to move on based on the results of an event. is implemented using IF statementThe smallest element of a programming language which expresses an action to be carried out..
Using IF and ELSE gives two possible choices (paths) that a program can follow. However, sometimes more than two choices are wanted. To do this, the statement ELSE IF is used.
This simple algorithmA sequence of logical instructions for carrying out a task. In computing, algorithms are needed to design computer programs. prints out a different message depending on how old you are. Using IF, ELSE and ELSE IF, the steps are:
- Ask how old you are
- IF you are 70 or older, say “You are aged to perfection!”
- ELSE IF you are exactly 50, say “Wow, you are half a century old!”
- ELSE say “You are a spring chicken!”
As a flow diagram, the algorithm would look like this:
PythonA high-level programming language. uses the statement elif, which stands for ‘ELSE IF.’
This flow diagram would be implemented in Python (3.x) as:
age = int(input("How old are you?"))
if age >= 70: print("You are aged to perfection!")
elif age == 50: print("Wow, you are half a century old!")
else: print("You are a spring chicken!")The programSequences of instructions for a computer. examines the value of age. If the inputted age is 70 or over, the program prints a particular message. If the inputted age is exactly 50, the program prints a different message. Otherwise (else) it prints a third message. Using elif allowed us to include a third choice in the program.
We can keep on adding elif statements to give us as many choices as we need:
age = int(input("How old are you?"))
if age >= 70: print("You are aged to perfection!")
elif age == 50: print("Wow, you are half a century old!")
elif age >= 18: print("You are an adult.")
else: print("You are a spring chicken!")When using an ‘if...else if’ statement, the program will stop checking as soon as it finds a positive answer. It is therefore very important to get the ‘if’ and ‘else’ conditions in the right order to make the program as efficient as possible.