04-Functions
ipynb22 kBPython · 43 cellsSlides of chapter 0
04 - Functions
Jupyter notebooks
This is a space where text and code come together to form a coherent document. Throughout the course, we will make use of Jupyter notebooks for illustration purposes and for experimentation.
Introduction
Functions are a set of code statements grouped together that get executed, often on specific inputs, to perform a specific task. So far, we have seen many built-in Python functions such as:
-
Input/Output:
input(),print() -
Type-casting:
int(),float(),str() -
Other:
type(),id(),len(),abs().
All of the above are built-in for the Python interpreter. Accordingly, no import statements are needed. We have also seen other useful functions from the math module, such as math.ceil(), math.sqrt(), math.log(), etc.
In general, a function is characterized by three things:
-
Its name: usually a descriptive name of the task being performed,
-
Its input parameters, and
-
Its return value.
Functions can return either a value or None.
Motivation
The motivation behind the use of functions boils down to multiple reasons:
-
Code re-usability: Often times, there is need to execute the same set of statements but at different stages within the same code. Defining the set of statements in a function simplifies the task of performing the same logic multiple times.
-
Decomposition: In addition to the above, it is generally a good idea to decompose a problem into subproblems, each of which can be solved by calling a specific function. This helps greatly when debugging complex code, by isolating the independent parts.
-
Abstraction: functions allow to hide implementation details from the user. For instance, one can simply use the
math.log()function by understanding that it takes two input parameters, without the need to know its implementation details (the algorithm used). -
Code Management: dividing big program into blocks aids in the long run, and the reasons above usually lead to good code management.
Calling a function (i.e., using a function)
Function with return value
If a function is named my_function() and takes as input some parameter x, it can be used by writing:
y = my_function(x) # result is stored in 'y'
For instance, the len() function takes 1 object (e.g., str, list, etc.) as input and returns the number of items in said input (an int):
s = "CSC243"
n = len(s)
type(n)Out [1] int
Another example is the input() function, which takes a str message to display and returns the str representation of what the user typed in:
user_input = input("Please enter a something: ")
type(user_input)Please enter a something: hello
Out [2] str
Function without a return value
A different function another_function() may also take as input x, but return nothing. In this case, the syntax for using it is:
another_function(x) # if it does not return a result
An example of a function that does not return a value is the print() function.
print("Output message")Output message
Notice that print() is used without being assigned a variable to store its result. If this is done, Python will not raise an error.
In such cases, there is an implicit return value of type NoneType. Recall from topic 1 that NoneType is a built-in data type in Python like int, float, str, etc.
Hence, for a function that does not return a result, assigning a return value to a variable will set it to the value None. Example:
result = print("This message is printed to the console.")
print(result)This message is printed to the console. None
When a function is called, the Python interpreter jumps to the function and executes statements
in the body. When the function is done executing, the interpreter jumps back to the part of program that called the
function. This happens when we reach the return statement or the end of the block of statements if no return is specified.
Defining a function
In Python, we can define our own functions. The general 'recipe' for creating a function is to answer the following questions:
| Question | Answer |
|---|---|
| What is the task to achieve? | Develop the main algorithm to complete the task |
| What are the inputs to my function? | Determine these variables |
| What is the return value of my function (if any)? | Determine this variable(s) |
Syntax
We use the def keyword to begin defining our function. Then, we specify a name for the function and the list of formal parameters (i.e., inputs to the function). Finally, we use the return keyword to indicate what the function must give back from the main algorithm.
def function_name(input_1, input_2, ..., input_N):
block of statements
return value
Example: defining our own (approximate) square-root function
| Question | Answer |
|---|---|
| What is the task to achieve? | Approx. square-root via the Bisection Method |
| What are the inputs to my function? | A number (x >= 0) and an error-tolerance (called eps or epsilon) |
| What is the return value of my function (if any)? | The variable storing the result (mid) |
def my_sqrt(x, epsilon):
if x == 1 or x == 0:
return x
elif x > 1:
low = 1
high = x
else: # if 0 < x < 1
low = x
high = 1
mid = (low + high)/2
while abs(mid*mid - x) > epsilon:
if mid*mid < x:
low = mid
else:
high = mid
mid = (low + high)/2
return midSince the my_sqrt() function defined above returns the (approximate) square-root, here is how we can call (use) it:
a = float(input("Enter a non-negative number: "))
b = my_sqrt(a, 1E-5)
print(b)Enter a non-negative number: 2 1.414215087890625
Default parameters
Functions can be defined to take default values for some parameters, if no values are provided to the function call for these parramters. For example, the math.log(x, base) which normally takes two arguments, will set the default value for base (the 2nd argument) to math.e = 2.71828..., if nothing is provided when the function is used. Accordingly, using math.log(2) will correspond to computing the natural logarithm of 2 or to math.log(2, math.e).
import math
result = math.log(2, math.e)
result_default = math.log(2) # calling function without 2nd argument
print("Are the resuls equal?", result == result_default)Are the resuls equal? True
Example: setting default parameters in our (approximate) square-root function
In our square-root function, we can pass a default value for epsilon by specifying it in the function header:
def my_sqrt(x, epsilon=1E-5):
if x == 1 or x == 0:
return x
elif x > 1:
low = 1
high = x
else: # if 0 < x < 1
low = x
high = 1
mid = (low + high)/2
while abs(mid*mid - x) > epsilon:
if mid*mid < x:
low = mid
else:
high = mid
mid = (low + high)/2
return midNow, we may use my_sqrt() without a value for epsilon; the default value above (1E-5) will be assumed:
x = 5
result = my_sqrt(5)
print(result)2.2360687255859375
Returning more than one value
To return more than one value, we can use a tuple as a return value. Let's look at an example that defines a function to find both the minimum and maximum values in a list L.
def min_max(L):
if len(L) == 0:
return tuple() # return empty tuple
elif len(L) == 1:
return (L[0], L[0])
else:
# begin algorithm
# initializations
minimum = L[0]
maximum = L[0]
for i in range(1, len(L)):
if L[i] < minimum:
minimum = L[i]
elif L[i] > maximum:
maximum = L[i]
# end of algorithm
return (minimum, maximum)L = [-1, -6, 0, 8, 10, 2, 5, 1]
(mini, maxi) = min_max(L)
print("minimum of", L, "is", mini)
print("maximum of", L, "is", maxi)
#result = min_max(L)
#print(result)minimum of [-1, -6, 0, 8, 10, 2, 5, 1] is -6 maximum of [-1, -6, 0, 8, 10, 2, 5, 1] is 10
Function namespace
Each function defines a namespace, also called a scope. The scope of a variable is the part of a program where the variable can be accessed. A local variable is a variable that can be accessed only inside the scope of a function. Accordingly, initializing a variable in a function makes it local in the function’s scope. When a function is called, a new stackframe is created in the execution stack to keep track of all names defined within the function and their current bindings.
Example (track on Python Tutor):
def max_val(x, y):
if x < y:
return y
else:
return x
z = max_val(3, 5)
print(z)5
Functions handling lists
In a function, a variable of type list can be:
-
An input argument
-
A local variable
-
A return value
Passing a list to a function and returning one from a function are done by assignment, which is efficient. This implies that if a list is passed as an input argument, changing the list in the function will change its actual values and not their copies. This is useful when we need to modify our list, for example when sorting it.
Example (track on Python Tutor):
def f(L, n, x):
L2 = [L[0]]*n
L[0] = x
L3 = L + L2
return L3
A = [0, 5, 9]
print("A:", A)
B = f(A, 2, -1)
print("A:", A)
print("B:", B)A: [0, 5, 9] A: [-1, 5, 9] B: [-1, 5, 9, 0, 0]
In the above example, we lose access to L2 since it is local to the function f. The memory reserved for storing L2 will be release back to the Operating System by the Python garbage collector. The garbage collector is a process that awakens to clean up objects in memory to which we don't have direct/indirect access.
Methods associated with data types
General Setup
Types in Python have available methods associated with them. The general setup is the following: if T is a data type and x is an object of type T, then the method f is is a member function of T; possibly with input paramters and a return value. Since it's a member, it should be accessed using . which is the member access operator.
Calling T.f:
○ v = x.f(input parameters), if f has a return value
○ x.f(input parameters), if f has no return value
Calling f(input parameters) without x. gives an error. If T is mutable, T.f may modify x by design.
Methods associated with the str data type
The str.split method
Recall the str.split() method, which is meant to be called on a str object. If s is a string, s.split(sep) returns a list of words (substrings) in s, using sep as a separator.
The default separator is " " (a whitespace). In other words, if we have a string which consists of words delimited by whitespaces " ", we can decouple the words using the split() method without passing it any argument.
Example:
my_string = "Lebanese American University"
L = my_string.split() # calling the split method
print(L) # printing the return value of the above ['Lebanese', 'American', 'University']
As can be seen from the above, the return value of the split() method is a list of strings.
The str.join method
In the opposite direction, we have the str.join() method. If sep is a string, and L is a list (or tuple) of strings, sep.join(L) returns a string consisting of the elements in L joined by sep. Example:
my_string = "Lebanese American University"
sep = " | "
L = ["Hello", "CSC", "243"]
my_string = sep.join(L)
print("After joining:", my_string)After joining: Hello | CSC | 243
Methods associated with the list type
The list.append method
We have seen the method list.copy(), which returns another list. Another method is list.append(e), which adds the object e to the end of a list. L.append(e) has the same effect on L as L = L + [e]. L.append modifies L and has no return a value.
Example:
L = ["Hello", "CSC"]
L.append("243")
print(L)['Hello', 'CSC', '243']
Recall that lists are implemented using contiguous memory cells so that access
to L[i] is very efficient, given i. If enough contiguous cells are available, e is added to the end of the list efficiently in memory. Otherwise, the whole list is copied to new place in memory and resized by appending enough contiguous cells. Thus, in the worst case, a single append takes in the order of the len(L) time, which is a lot for long lists. However, the overhead on a long sequence of append operations is not substantial; this an advantage over L = L + [e], which always creates a new list.
The list.extend method
L.extend(L2), where L2 is a list, adds the items in L2 to the end of L. Like L.append(), L.extend() mutates L and has no return value.
L.extend(L2) has the same effect on L as L = L + L2
L = [1, 2]
L2 = [3, 4]
L.extend(L2)
print(L)[1, 2, 3, 4]
Useful references
-
For a list of built-in Python functions, visit the official Python documentation.
-
To see other
listmethods, visit the official Python Documentation.