At any part of a Python code you can define a function with the def
keyword.
Mind the code block (identation) and colon.
def function_name(n):
"... code ..."
The following is a function definition, a recipe which tells what to do if the function is called.
def square(L):
new_L = []
for i in L:
new_L.append(i*i)
return new_L
After the def
keyword there is the name of the function (how we would like to call it).
After that the parameter(s), comma separated, in parenthesis. After the colon there is the function body, that part is executed when the function is called.
Inside the function body there is a return
keyword which tells the function to stop and the result of the function will be the value after the word return
.
To call a function write its name and the necessary parameters in a parenthesis (in the example: a single parameter which is a list):
square([4, 3, 5])
One can call the function to operate on a previously defined variable.
numbers = [5, 1, 8]
squared_numbers = square(numbers)
print numbers, squared_numbers
If the function is correct then the result is the list of squared numbers and nothing unexpected happens, but look what happens in the following solution.
def square2(L):
i = 0
while i < len(L):
L[i] = L[i] ** 2
i += 1
return L
numbers = [5, 1, 8]
squared_numbers = square2(numbers)
print numbers, squared_numbers
The function modified its parameter, the original list, and also returned the modified list.
We will detail on this issue later in the semester, but for now: write functions which do not modify their parameters.
Parameters are listed in a comma separated list.
def dot_product(v1, v2):
result = 0
for i in range(len(v1)):
result += v1[i] * v2[i]
return result
dot_product([2, 3, 5], [1, 5, 2])
Parameters can be any objects with any type. A function can have any given number of parameters, even 0. One can think of a nullary function as a constant, but nevertheless the parenthesis is mandatory.
def empty_list():
return []
L = empty_list()
L.append(5)
print L
A function (at first glance) is called in this way:
A method looks like this:
L = [5, 2, 4]
L.sort()
print L
The sort
is a built in method of lists (a number itself cannot be sorted).
For example there is a similar function called sorted
:
L = [5, 2, 4]
new_L = sorted(L)
print L, new_L
The function sorted
does not modify the list itself, but returns a new, sorted list.
This is a common practice with methods and functions, but not a law.
None
)Later we will learn how to write methods.
return
¶The command return
exits the function without processing any further parts of the function body. One can take advantage of this behaviour:
def is_a_prime(n):
for divisor in range(2, n/2):
if n % divisor == 0:
return False
return True
print is_a_prime(15)
print is_a_prime(23)
If the function arrives at a true divisor then returns immediately because there is no need to look further.
The True
value is returned only if neither of the numbers were true divisors.
Remark: break exits a loop (only a loop and only one of them), and return exits a function (only a function and only one of them, but breaks any loop in that function).
One can return None
to represent "no value is returned".
If a function has no return
command then the result will be None
.
For example is you forgot to write return
or you wrote it to the wrong place.
Remark: the .sort()
method results None
, but it sorts the list as a side-effect.
L = [3, 2, 1, 4]
l = L.sort()
print l, L
You can call any function (once defined) inside other functions as well. It is not only possible but encouraged!
Best if you write no more than 4-5 line functions and put those functions together to solve bigger problem. This way you functions will be shorter and harder to make mistakes. The goal and the mechanism of the function should be clear by reading its name and its parameters.
An example:
Write a function which has one parameter, a list, and finds the smallest and greatest elements in the list. Also replace the extremal values with a 0 value!
How to solve the task?
For example in this task the subtasks are:
Lets solve these
def minimum(L):
min_elem = float("inf")
for e in L:
if e < min_elem:
min_elem = e
return min_elem
def maximum(L):
max_elem = -float("inf")
for e in L:
if e > max_elem:
max_elem = e
return max_elem
def erase(L, elem):
newL = L[:] # makes a copy of L (sublist from the beginning to the end)
for i in range(len(newL)):
if newL[i] == elem:
newL[i] = 0
return newL
Now you have everything to write the main function:
def min_max_erase(L):
minelem = minimum(L)
maxelem = maximum(L)
newL = erase(L, minelem)
newL = erase(newL, maxelem)
return newL
min_max_erase([2, 3, 1, 4, 6, 2, 9, 3, 1, 3, 1, 9, 3, 9])
min_max_erase([])
min_max_erase([1, 1, 1, 2])
min_max_erase([1,1])
A shorter solution for the last part (last three lines of the main function):
return erase(erase(L, minelem), maxelem)
You can solve this in one big function:
def min_max_erase2(L):
min_elem = float("inf")
for e in L:
if e < min_elem:
min_elem = e
max_elem = -float("inf")
for e in L:
if e > max_elem:
max_elem = e
newL = L[:] # makes a copy of L (sublist from the beginning to the end)
for i in range(len(newL)):
if newL[i] == min_elem:
newL[i] = 0
for i in range(len(newL)):
if newL[i] == max_elem:
newL[i] = 0
return newL
min_max_erase2([2, 3, 1, 4, 6, 2, 9, 3, 1, 3, 1, 9, 3, 9])
The first solution is
The second solution works, too.
Write a function which sorts a given list (a single parameter) but write it on your own, without using the builtin sort
method or the sorted
function!
A simple solution is the so-called bubble sort. See a musical and a dance performance of the algorithm.
def bubble(L):
newL = L[:]
for i in range(len(newL) - 1):
for j in range(len(newL) - i - 1):
if newL[j] > newL[j + 1]:
temp = newL[j]
newL[j] = newL[j + 1]
newL[j + 1] = temp
return newL
bubble([2, 3, 1, 4, 6, 2, 9, 3, 1, 3, 1, 9, 3, 9])
bubble(range(10, 0, -1))
Lets print the actual state during the algorithm:
def bubble_print(L):
newL = L[:]
for i in range(len(newL) - 1):
for j in range(len(newL) - i - 1):
print newL # print here
if newL[j] > newL[j + 1]:
temp = newL[j]
newL[j] = newL[j + 1]
newL[j + 1] = temp
return newL
bubble_print(range(10, 0, -1))
There are more sophisticated (and faster) algorithms, you will learn those in the Theory of Algorithms class.
First subtask is finding a minimum.
def armin(L):
min_place = 0
min_elem = L[0]
for i in range(len(L)):
if L[i] < min_elem:
min_elem = L[i]
min_place = i
return min_place
armin([3,2,100,-1,1])
Then solve the whole task.
def sort_min(L):
newL = L[:]
for i in range(0, len(newL)-1):
j = armin(newL[i:])
newL[i], newL[i + j] = newL[i + j], newL[i]
return newL
sort_min([3,2,100,-1,1])