Functions

You are likely already comfortable with calling functions such as:

In this section we’re going to explore other functions and methods available as part of Python’s core capabilities and in other modules. An important technical resource you probably will come across often is The Python Standard Library.

Built-in functions

Python comes with a bunch of functionality that you can use without having to explicitly enable anything. This includes things like integers, strings, lists, print()ing, file open()ing etc.

First, lets have a peek at the built-in functions. There is a page describing these under the “Library Reference”, in a page called Built-in Functions. There we find the documentation for many of the functions we’ve already been using, for example print() and max().

It is worth, over time, becoming familiar with the various functions that are available. Some are quite useful for everyday work and some are more niche.

Exercise

Copy the following code into a new script hello.py:

my_name = ...

name_length = ...

print(f"Hello {my_name}! Your name is {name_length} characters long")

Replace the first ... with a call to a built-in function which will read input from the person running the script. Replace the second ... with a call to a function which will give the length of the string my_name. When executed, the script should print out:

Please tell me your name: Jean
Hello Jean! Your name is 4 characters long

If you need it, you can search through the built-in functions page to find the appropriate functions.

To get input from the person running your script, you can use the function input(). And to get the length of your variable you can call len().

hello.py
my_name = input("Please tell me your name: ")

name_length = len(my_name)

print(f"Hello {my_name}! Your name is {name_length} characters long")
Please tell me your name: Jean
Hello Jean! Your name is 4 characters long

Methods for built-in data types

Python has a bunch of built-in data types, the details of them all are on the page called Built-in Types. That is the place to go to check what you can do with a str, an int, a list or a dict. There’s also a few other built-in types you might want to look into in the future such as complex, set and tuple.

These types being built-in means that you don’t need to explicitly enable their use and most have core-language syntax to create them.

For example, the code

animal = "horse"

creates a variable called animal from the string literal "horse" which is of the type str. This data type is built into the language and so the functionality that it has is documented on built-in type str.

This means that when we do:

animal.capitalize()

it is looking at the data type of the variable animal, seeing that it is a str and then using the capitalize function that’s available for that type to do the work.

Exercise

Have a look at the documentation page for the functions that you can call on strings.

Experiment with one or two and see if you can understand the documentation. Start by trying to answer the following:

  1. Given a string like s = "what is your name", find a function which can split s into a list like ["what", "is", "your", "name"]
  2. Given a list like ["a", "b", "c"], find a function which can join it together into a string like "a-b-c"

You can split any string using the str.split function. By default it splits on spaces:

s = "what is your name"
s.split()
['what', 'is', 'your', 'name']

Join a list

You can join a list together by using the str.join function. Note that in front of the dot you put the string that you want to join with, and you pass the list you want to join together as an argument.

l = ["a", "b", "c"]
"-".join(l)
'a-b-c'
l = ["a", "b", "c"]
":".join(l)
'a:b:c'
l = ["a", "b", "c"]
" ".join(l)
'a b c'
Exercise

Change the message in encode.py to use both upper and lower case letters:

message = "SOS We have hit an iceberg and need help quickly"

When you now run the script with python encode.py you will find that it gives you a KeyError. This is because it is looking for an upper case “S” in the dictionary letter_to_morse and not finding one (dictionary keys are case-sensitive).

Read through the documentation for the string methods to find one that might help convert the letter you have into one that matches the keys in the dictionary. You should be able to add a single line of code in the loop straight after for letter in message:.

The function str.lower gives you back a copy of the string, but all made into lower case.

In our situation, the first letter is “S” and so letter.lower() will give us "s".

encode.py
letter_to_morse = {
    'a':'.-', 'b':'-...', 'c':'-.-.', 'd':'-..', 'e':'.', 'f':'..-.', 
    'g':'--.', 'h':'....', 'i':'..', 'j':'.---', 'k':'-.-', 'l':'.-..', 'm':'--', 
    'n':'-.', 'o':'---', 'p':'.--.', 'q':'--.-', 'r':'.-.', 's':'...', 't':'-',
    'u':'..-', 'v':'...-', 'w':'.--', 'x':'-..-', 'y':'-.--', 'z':'--..',
    '0':'-----', '1':'.----', '2':'..---', '3':'...--', '4':'....-',
    '5':'.....', '6':'-....', '7':'--...', '8':'---..', '9':'----.', ' ':'/'
}

message = "SOS We have hit an iceberg and need help quickly"

morse = []

for letter in message:
    letter = letter.lower()  #  ← We have added this line of code
    morse_letter = letter_to_morse[letter]
    morse.append(morse_letter)

morse_message = " ".join(morse)

print(f"Incoming message: {message}")
print(f"   Morse encoded: {morse_message}")
Terminal/Command Prompt
python encode.py
Incoming message: SOS We have hit an iceberg and need help quickly
   Morse encoded: ... --- ... / .-- . / .... .- ...- . / .... .. - / .- -. / .. -.-. . -... . .-. --. / .- -. -.. / -. . . -.. / .... . .-.. .--. / --.- ..- .. -.-. -.- .-.. -.--