Examples of Functions¶
Example: Reporting the Square of a Number¶
In this example, we will 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 ", n, " is ", n**2, ".", sep='')
In the cell below, we have 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]
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.
Example: Summing the First n
Positive Integers¶
In the following cell, we write a function called sum_first()
that takes a single parameter n
, and returns the sum of the first n positive integers.
def sum_first(n):
total = 0
for i in range(1,n+1):
total = total + i
return total
We now call sum_first()
on 100, and also on 237, printing the return value for each function call.
print(sum_first(100))
print(sum_first(237))
5050
28203
Example: Factorials¶
We will now write a function called fact()
that takes in one argument, assumed to be an integer, and returns the factorial of that integer.
def fact(n):
product = 1
for i in range(1,n+1):
product = product * i
return product
We will use our function calculate the factorials of 3, 5, 10, and 20.
print(fact(3))
print(fact(5))
print(fact(10))
print(fact(20))
6
120
3628800
2432902008176640000
Example: sum_power
Function¶
In the cell below, we create a function called sum_power
. The function has two parameters, x
and n
. The parameter x
is intended to be a list. The parameter n
should be an int
with a default value of 1
. The function should raise each element to the power of n
, sum the resulting values, and then return this sum.
def sum_power(x, n=1):
total = 0
for i in range(0, len(x)):
total += x[i]**n
return total
We test our function in the cell below.
A = [4,-3,1]
print(sum_power(A))
print(sum_power(A, 2))
print(sum_power(A, 3))
print(sum_power(A, 7))
2
26
38
14198
Example: find_item
Function¶
In the cell below, we define a function called find_item
that has three parameters, x
, item
, and first
. The parameter x
is expected to be a list. The parameter first
should have a default value of True
. The function should behave as follows:
If
first == True
, then the function should search for the first time thatitem
appears inx
, and should return the index of that occurrence.If
first == False
, then the function should search for the last time thatitem
appears inx
, and should return the index of that occurrence.If
item
does not appear inx
, then the function should returnNone
.
def find_item(x, item, first=True):
idx = None
for i in range(0, len(x)):
if x[i] == item:
idx = i
if first:
return idx
return idx
After defining your function, use the following lines of code to test it.
letter_list = ['B', 'C', 'A', 'D', 'A', 'C', 'B', 'A', 'D']
print(find_item(letter_list, 'A'))
print(find_item(letter_list, 'A', first=False))
print(find_item(letter_list, 'D'))
print(find_item(letter_list, 'D', first=False))
print(find_item(letter_list, 'E'))
print(find_item(letter_list, 'E', first=False))
2
7
3
8
None
None
Example: Division with Remainder¶
Write a function div_w_remainder()
that takes two arguments, num
and div
, and returns the number of times that div
evenly divides num
(i.e. the quotient), as well as the remainder of num
after division by div
. Coerce the remainder into an integer.
def div_w_remainder(num, div):
quotient = int(num/div)
remainder = num % div
return (quotient, remainder)
We will now consider several examples to test our function.
q, r = div_w_remainder(17, 3)
print('Quotient: ', q)
print('Remainder:', r)
Quotient: 5
Remainder: 2
q, r = div_w_remainder(459, 17)
print('Quotient: ', q)
print('Remainder:', r)
Quotient:
27
Remainder: 0
q, r = div_w_remainder(6237, 13)
print('Quotient: ', q)
print('Remainder:', r)
Quotient: 479
Remainder: 10
Example: Locating Elements in a List¶
Write a function called locate
. The function should take two arguments: a list called x
, and another variable called item
.
The function should return two values: A list of indices at which the element in x
is equal to item
, and a count of the number of times that item
appears in x
.
def locate(x, item):
index_list = []
for i in range(0, len(x)):
if x[i] == item:
index_list.append(i)
return (index_list, len(index_list))
A list of student grades is provided in the cell below. Call locate()
five times. In each function call, pass in grades
for x
. For item
, use each of the following values: 'A'
, 'B'
, 'C'
, 'D'
, and 'F'
.
For each function call, print out a message of the following form:
A: indices = [......], count = ##
grades = ['A', 'D', 'A', 'C', 'B', 'F', 'A', 'D', 'C', 'B', 'F', 'A', 'C',
'B', 'A', 'B', 'B', 'C', 'B', 'F', 'D', 'D', 'A', 'C', 'B']
for letter in ['A', 'B', 'C', 'D', 'F']:
idx, c = locate(grades, letter)
print(str(letter) + ': indices = ' + str(idx) + ', count = ' + str(c) )
A: indices = [0, 2, 6, 11, 14, 22], count = 6
B: indices = [4, 9, 13, 15, 16, 18, 24], count = 7
C: indices = [3, 8, 12, 17, 23], count = 5
D: indices = [1, 7, 20, 21], count = 4
F: indices = [5, 10, 19], count = 3