Lesson 09 - Introduction to Functions

The following topics are discussed in this notebook:

  • Defining functions.
  • Parameters and arguments.
  • Return values.

Additional Resources

A function is a sequence of instructions that has been given a name. Once they are defined, functions can be used anywhere within your project. If you find that there is a task that you are repeating often, and that requires several lines of codes, it might be a good idea to group those lines of code together into a function.

We start by defining a (very) simple function below.

In [1]:
def rick_roll():
    print("Never gonna give you up. Never gonna let you down.")

Notice that notice was printed when we defined the function. The function only executes when it is actually called.

In [2]:
rick_roll()
Never gonna give you up. Never gonna let you down.
In [3]:
for n in range(0,5):
    rick_roll()
Never gonna give you up. Never gonna let you down.
Never gonna give you up. Never gonna let you down.
Never gonna give you up. Never gonna let you down.
Never gonna give you up. Never gonna let you down.
Never gonna give you up. Never gonna let you down.

Poviding Information to Functions

The function rick_roll() defined above is not vary useful (for a few reasons). In particular, it doesn't take any inputs. There are occassions when you will want to write functions that take no inputs, but functions are generally more useful when we are able to supply them information that affects how they function.

The function below prints the square of a number that is supplied to it.

In [4]:
def square(n):
    print(n**2)

The variable n in the function definition above is called a parameter. We would like for our function to work on any number that is supplied to it, and so we use the parameter n to serve as a placeholder for any number supplied to square(). The parameter n has a new value assigned to it each time the function is called. Any specific number supplied to the function is referred to as an argument.

In [5]:
square(2)
square(3.6)
square(-3)
#square('circle')
4
12.96
9

Just to clarify, when you see a function definition such as:

def my_function(x):

The variable between the parentheses is referred to as a parameter. A parameter is simply a placeholder, and has no default value. However, any specific number that is substituted in for the parameter is called an argument. For example, consider the following expression:

my_function(7)

In this case 7 is an argument that is being "plugged in" to the parameter x.

� Exercise

Write a function called square_message(). The function should take one argument, n, and should print the message:

The square of [n] is [n**2].
In [6]:
def square_message(n):
    print("The square of " + str(n) + " is " + str(n**2) + ".")

In the cell below, add a loop that applies the function square_message() to every element of the list A.

In [7]:
A = [12, 34, 89, 17, 23, 49, 87, 34, 89, 71, 34, 58, 97, 23, 48, 95, 71, 34, 89, 57, 13, 48, 97, 54]

for i in range(0, len(A)):
    square_message(A[i])
The square of 12 is 144.
The square of 34 is 1156.
The square of 89 is 7921.
The square of 17 is 289.
The square of 23 is 529.
The square of 49 is 2401.
The square of 87 is 7569.
The square of 34 is 1156.
The square of 89 is 7921.
The square of 71 is 5041.
The square of 34 is 1156.
The square of 58 is 3364.
The square of 97 is 9409.
The square of 23 is 529.
The square of 48 is 2304.
The square of 95 is 9025.
The square of 71 is 5041.
The square of 34 is 1156.
The square of 89 is 7921.
The square of 57 is 3249.
The square of 13 is 169.
The square of 48 is 2304.
The square of 97 is 9409.
The square of 54 is 2916.

Return Values

All of the function we have written so far have printed some sort of message. However, we will not always desire this sort of behavior. In fact, most of the pre-defined functions we have seen in this course print nothing at all, but instead provide some sort of output that can be printed, or stored into a variable.

For example, the sum() function takes a list as an input, and provides the sum of the values in the list as the output. When a function provides an output, that output is called a return value.

We can define functions that have return values using the return keyword.

In [8]:
def half(x):
    return x/2
In [9]:
print(half(100))
print(half(35))
print(half(3.14159))
50.0
17.5
1.570795
In [10]:
b = half(73452)
In [11]:
one_eighth = half(half(half(20)))
print(one_eighth)
2.5
In [12]:
num = 10000000000
count = 0

while num > 1:
    count += 1
    num = half(num)

print(num)
print(count)
0.5820766091346741
34

� Exercise

Modify the cell above to also print out the number of times that num was halved.

� Exercise

Write a function called radians(). The function should have a single parameter, deg, intended to represent some number of degrees in an angle. The function should return deg converted to radians.

In [13]:
def radians(deg):
    rad = deg * 3.14159 / 180
    return rad

Call radians() on 60, 90, 137, 180, and 219.

In [14]:
print(radians(60))
print(radians(90))
print(radians(137))
print(radians(180))
print(radians(219))
1.0471966666666666
1.570795
2.3910990555555554
3.14159
3.822267833333333
In [15]:
print(round(radians(60), 4))
1.0472

� Exercise

Write a function called fact() that takes in one argument, and returns the factorial of that argument.

In [16]:
def fact(n):
    
    nFact = 1
    for i in range(1,n+1):
        nFact = nFact * i
    return nFact

Call fact() on 3, 5, 10, and 20.

In [17]:
print(fact(3))
print(fact(5))
print(fact(10))
print(fact(20))
6
120
3628800
2432902008176640000

� Exercise

Write a function called sumN() that take a single parameter n, and returns the sum of the first n positive integers.

In [18]:
def sumN(n):
    
    nsum = 0
    
    for i in range(1,n+1):
        nsum = nsum + i
        
    return nsum
In [19]:
print(sumN(100))
print(sumN(1000))
5050
500500

Absolute Value

In [20]:
def abs(x):
    
    if (x < 0):
        absVal = -x
    else:
        absVal = x
    return absVal
In [21]:
print(abs(9))
print(abs(-3.8))
9
3.8
In [22]:
def abs2(x):
    if(x < 0):
        return -x
    return x

Functions with Multiple Parameters

It is possible for functions to have two or more parameters. Consider the following example.

In [23]:
def power(a,b):
    return a**b
In [24]:
print( power(2,5) )
print( power(3,4) )
print( power(10,2) )
print( power(2,10) )
32
81
100
1024

� Exercise

Write a function num_divisions() that takes two arguments, div and num, and returns the number of times that div evenly divides num.

In [25]:
def num_division(num, div):
    
    temp = num
    count = 0
    
    while(temp % div == 0):
        temp = temp / div
        count += 1
        
    return count
    
In [26]:
print(num_division(500,5))
print(num_division(42,5))
3
0

� Exercise

Write a function called SumOfSquares that takes a list as an argument, and returns the sum of the squares of the list.

In [27]:
def SumOfSquares( myList ):
    
    total = 0
    for i in range(0, len(myList)):
        total += myList[i]**2
        
    return total
In [28]:
print(SumOfSquares([4,2,1]))
print(SumOfSquares([-4,2,-1]))
21
21

� Exercise

Write a function called SumPower that takes a list and a integer, and returns the sum of the elements of that list raised to the integer.

In [29]:
def SumPower(myList, Exp=1):
    
    total = 0
    
    for i in range(0, len(myList)):
        total += myList[i]**Exp
        
    return total 
In [30]:
A = [4,2,1]
print(SumPower(A, 2))
print(SumPower(A, 3))
print(SumPower(A, 7))
21
73
16513
In [31]:
print(SumPower(A,1))
print(SumPower(A))
7
7

� Exercise

Write a function called CountItems that takes a list and a some other argument, and returns the number of times that the argument appears in the list.

In [32]:
def CountItems(myList, Term):
    
    count = 0
    for i in range(0, len(myList)):
        if myList[i] == Term:
            count += 1
        
    return count
In [33]:
Grades = ['A', 'A', 'C', 'B', 'F', 'D', 'C', 'B', 'F', 'A']

print(CountItems(Grades, 'A'))
print(CountItems(Grades, 'B'))
print(CountItems(Grades, 'C'))
print(CountItems(Grades, 'D'))
print(CountItems(Grades, 'E'))
print(CountItems(Grades, 'F'))
3
2
2
1
0
2