1.3 What if...?
The third conversion, from abbreviated country names to full names, can’t be written as a simple formula, because each abbreviation is expanded differently.
What I need is the Python code equivalent of:
- if the name is ‘UK’, return ‘United Kingdom’,
- otherwise if the name is ‘USA’, return ‘United States’,
- otherwise return the name.
The last part basically says that if the name is none of the known abbreviations, return it unchanged. Translating the English sentence to Python is straightforward.
In []:
def expandCountry (name):
if name == 'UK': # if the name is 'UK'
return 'United Kingdom'
elif name == 'USA': # otherwise if the name is 'USA'
return 'United States'
else: # otherwise
return name
expandCountry('India') == 'India'
Out[]:
True
Note that ‘otherwise if’ is written 'elif' in Python, not 'else if' . As you might expect, ‘if’, ‘elif’ and ‘else’ are reserved words.
The computer will evaluate one condition at a time, from top to bottom, and execute only the instructions of the first condition that is true. Note that there is no condition after 'else' , it is a ‘catch all’ in case all previous conditions fail.
Note again the colons at the end of lines and that code after the colon must be indented. That is how Python distinguishes which lines of code belong to which condition.
There are almost always many ways to write the same function. A conditional statement does not need to have an 'elif' or 'else' part. In that case, if the condition is false, nothing happens. Here is the same function, written differently.
In []:
def expandCountry (name):
if name == 'UK':
name = 'United Kingdom'
if name == 'USA':
name = 'United States'
return name
You will see later this week an example of an ‘if-else’ statement, i.e. without the 'elif' part.
Exercise 3 What if…?
Complete Exercise 3 in the Exercise notebook 3 to practise writing functions with conditional statements.