3.7.3 else and elif statements

else and elif statements allow you to test further conditions after the condition tested by the if statement and execute alternative statements accordingly. They are an extension to the if statement and may only be used in conjunction with it.

If you want to execute some alternative statements if an if test fails, then use an else statement as follows:

      if [condition]:
          [Some statements executed only if [condition] is true]
          [Some statements executed only if [condition] is false]

      [rest of program]

If the first condition is true the indented statements directly below it are executed and Python jumps to [rest of program] Otherwise the nested block below the else statement is executed, and then Python proceeds to [rest of program].

The elif statement is used to test further conditions if (and only if) the condition tested by the if statement fails:

      x = input("Enter a number")

      if 0 <= x <= 10:
          print "That is between zero and ten inclusive"
      elif 10 < x < 20:
          print "That is between ten and twenty"
          print "That is outside the range zero to twenty"

Write a program to read in two numbers from the user, and then print them out in order.

Modify the program to print three numbers in order. The code for this program will not be too complicated once it is written, but thinking about the logical steps that must be taken in order to sort the three numbers in the most efficient way possible is not easy. Make notes on paper before writing any Python; perhaps draw some diagrams of the flow of the program as it tests the numbers.