Functions

  • Built-in Functions

  • Standard Library

  • Defining Functions

  • basic function syntax

  • examples

  • the return statement

  • the pass statement

  • value of functions: modularity and reusability

  • arguments

  • doc strings

  • positional arguments

  • keyword arguments

  • *args

  • **kwargs

We spent time learning basic Python types and operations and working with the REPL. It’s time to write some programs. Let’s write our first program and learn an important, maybe the most important, built-in function: the print function. Python has many built-in functions to help make writing programs easier.

Open up your text editor or IDE and type-in or copy the following::

print('Hello World!')

Save the program as hello.py. Navigate to the same directory where you saved the program and type::

>>> python hello.py
Hello World!

To define our own function, the syntax is the following::

def function_name(arguments):
    (body of function)

Here is a simple example that converts a Celcius temperature to Fahrenheit:

def C_to_F(C):
    return (9 / 5) * C + 32

>>> print(C_to_F(27))
80.6

Here is another example that takes the average of three numbers:

def average(a, b, c):
        return (a + b + c)/3
>>> print(average(1, 3, 5))
3.0

Here is another example that finds the median of four numbers:

def median(a, b, c, d):
    lst = []
    lst.append(a)
    lst.append(b)
    lst.append(c)
    lst.append(d)
    lst.sort()
    return (lst[1] + lst[2])/2
>>> print(median(10, 3, 8, 5))
6.5

We will learn better ways to build lists soon. As it is, the code shows off some of the things we have learned about lists so far.

Define a function that “mirrors” a word:

mirror_string('word') = 'worddrow'

Here is the function:

def mirror(string):
    return string + string[::-1]
>>> print(mirror('Alex'))
AlexxelA

Here is an example for a later section after we discuss looping.

Problem We are given the following dictionary. Customer numbers serve as the keys and lists containing a customer name and last month’s spending are the values. Find the average amount spent per customer last month.:

customers = {'001': ['Alex', 100.00],
'314': ['Sonya', 25.25],
'174':['Erika', 30.91],
'521': ['Anthony', 34.56],
'231': ['Joseph', 13.76]
}

The exercises that follow are similar to problems found in CodeWars. CodeWars is an excellent website for practicing to code. The website has lots of well-defined problems for a wide variety of programming languages. THe problems vary in difficulty. Once you solve a problem you are able to see the code others have written. This is useful in improving your skill at reading and writing code. You can also write your own problems and learn about testing code.

Problem 1: Write a function, counter(string), that counts all of the left and right parenthesis in a string and outputs a list of two integers for these counts. For example:

counter('(') = [1, 0]
counter(')))') = [0, 3]
counter('Python(coding(is)fun!') = [2, 2]

Problem 2: Write a function, trifib(n), that takes a single positive integer, n <= 30, as input and returns a single integer. The function generates the nth term in this sequence: 1, 1, 1, 3, 5, 9, 17, …. The first three terms are 1 and after that each term is the sum of the previous three terms. For example:

trifib(1) = 1 # by definition
trifib(3)  =  1 # by definition
trifib(4)  =  3   # because 1 + 1 + 1 = 3
trifib(8)  =  31 # because 5 + 9 + 17 = 31

Problem 3: Write a Python function called sum_of_thirds(int) that takes a positive integer divides it by three, drops the remainder and repeats this process with each divisor. The function then returns the sum of all the quotients. For example:

20 creates the sequence: 6, 2 and the sum is 6 + 2 = 8. So:

sum_of_thirds(20) = 8

45 creates the sequence: 15, 5, 1 and the sum is 15 + 5 + 1 = 21. So:

sum_of_thirds(45) = 21