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.
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.
rick_roll()
for n in range(0,5):
rick_roll()
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.
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.
square(2)
square(3.6)
square(-3)
#square('circle')
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].
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
.
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])
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.
def half(x):
return x/2
print(half(100))
print(half(35))
print(half(3.14159))
b = half(73452)
one_eighth = half(half(half(20)))
print(one_eighth)
num = 10000000000
count = 0
while num > 1:
count += 1
num = half(num)
print(num)
print(count)
� 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.
def radians(deg):
rad = deg * 3.14159 / 180
return rad
Call radians()
on 60, 90, 137, 180, and 219.
print(radians(60))
print(radians(90))
print(radians(137))
print(radians(180))
print(radians(219))
print(round(radians(60), 4))
� Exercise
Write a function called fact()
that takes in one argument, and returns the factorial of that argument.
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.
print(fact(3))
print(fact(5))
print(fact(10))
print(fact(20))
� Exercise
Write a function called sumN()
that take a single parameter n
, and returns the sum of the first n positive integers.
def sumN(n):
nsum = 0
for i in range(1,n+1):
nsum = nsum + i
return nsum
print(sumN(100))
print(sumN(1000))
def abs(x):
if (x < 0):
absVal = -x
else:
absVal = x
return absVal
print(abs(9))
print(abs(-3.8))
def abs2(x):
if(x < 0):
return -x
return x
It is possible for functions to have two or more parameters. Consider the following example.
def power(a,b):
return a**b
print( power(2,5) )
print( power(3,4) )
print( power(10,2) )
print( power(2,10) )
� Exercise
Write a function num_divisions()
that takes two arguments, div
and num
, and returns the number of times that div
evenly divides num
.
def num_division(num, div):
temp = num
count = 0
while(temp % div == 0):
temp = temp / div
count += 1
return count
print(num_division(500,5))
print(num_division(42,5))
� Exercise
Write a function called SumOfSquares
that takes a list as an argument, and returns the sum of the squares of the list.
def SumOfSquares( myList ):
total = 0
for i in range(0, len(myList)):
total += myList[i]**2
return total
print(SumOfSquares([4,2,1]))
print(SumOfSquares([-4,2,-1]))
� 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.
def SumPower(myList, Exp=1):
total = 0
for i in range(0, len(myList)):
total += myList[i]**Exp
return total
A = [4,2,1]
print(SumPower(A, 2))
print(SumPower(A, 3))
print(SumPower(A, 7))
print(SumPower(A,1))
print(SumPower(A))
� 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.
def CountItems(myList, Term):
count = 0
for i in range(0, len(myList)):
if myList[i] == Term:
count += 1
return count
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'))