Selection in programmingUsing ELSE IF to provide more choices

When designing programs, there are often points where a decision must be made. This decision is known as selection, and is implemented in programming using IF statements.

Part ofComputer ScienceProgramming

Using ELSE IF to provide more choices

In , is implemented using IF .

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 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:

A flowchart asking for your age will output the response 'wow, you are half a century old' if the age is under 70 years old but equal to 50 years old.

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 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.