More on IF

We have seen how to write if-else statements. We can make more complex if statements by using the elif keyword, which is equivalent to "else if".

The syntax is as follows:

1
2
3
4
5
6
if <condition>:
    <statements>
elif <condition2>:
    <statements>
else:
    <statements>

The following video demonstrates this in use in Python.

Here is another example showing if ... elif ... else:

1
2
3
4
5
6
7
8
9
weather = input("What is the weather like: ")
if weather == "raining":
    print("Take an umbrella")
elif weather == "cold":
    print("Take a coat")
elif weather == "sunny":
    print("Wear sunscreen")
else:
    print("Have a good day, whatever the weather!")

Exercises

  1. Write a function that asks the user to input a number between 1 and 20. Give a response which indicates if the number is either within the range, too high or too low.
  2. Write a function which inputs the names of two football teams, and the score of one team followed by the score of the other team. Your function should calculate how many points each team gets (3 for a win,1 for a draw, 0 if they lose).