13/09/2024
Chapter 03
Functions
CIVL1000
Computer Science
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey Adapted: Miguel Gomes da Costa Junior
Functions
• In the context of programming, a function is a named sequence of
statements that performs a computation.
• When you define a function, you specify the name and the sequence
of statements.
• Later, you can “call” the function by name.
• The word “invocation” is used as synonym.
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 2
1
13/09/2024
3.1 Functions calls
• We have already seen one example of a function call:
• The name of the function is type, the expression in
>>> type(42)
parentheses is called the argument of the function,
<class 'int'>
and the result is the type of the argument.
• A function “takes” an argument and “returns” a return value.
• Python provides functions that convert values from one type to
another.
• The int function takes any value and >>> int('32')
converts it to an integer, if it can, or 32
complains otherwise: >>> int('Hello')
ValueError: invalid literal for int(): Hello
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 3
3.1 Functions calls
• int can convert floating-point values to integers, >>> int(3.99999)
but it doesn’t round off; it chops off the fraction 3
part: >>> int(-2.3)
-2
• float converts integers and strings to floating- >>> float(32)
point numbers: 32.0
>>> float('3.14159')
3.14159
• str converts its argument to a string: >>> str(32)
'32'
>>> str(3.14159)
'3.14159'
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 4
2
13/09/2024
3.2 Math functions
• Python has a math module that provides most of the familiar mathematical
functions.
• A module is a file that contains a collection of related functions.
• Before we can use the functions in a module, we have to import it with an
import statement:
>>> import math
• This statement creates a module object named math. If you display the
module object, you get some information about it:
>>> math
<module 'math' (built-in)>
• The module object contains the functions and variables defined in the
module.
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 5
3.2 Math functions
• The module object contains the functions and variables defined in the
module.
• To access one of the functions, you have to specify the name of the module and
the name of the function, separated by a dot (also known as a period). This
format is called dot notation.
• The first example uses math.log10 to compute a signal-to-noise ratio in decibels.
The math module also provides log, which computes logarithms base e.
>>> ratio = signal_power / noise_power (Note: assume that signal_power
>>> decibels = 10 * math.log10(ratio) and noise_power are defined).
• The second example finds the sine of radians. The variable name radians is a
hint that sin and the other trigonometric functions take arguments in radians.
>>> radians = 0.7
>>> height = [Link](radians)
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 6
3
13/09/2024
3.2 Math functions
• To convert from degrees to radians, divide by 180 and multiply by π:
• The expression [Link] gets the variable π from the math module. Its value is
a floating-point approximation of π,accurate about 15 digits.
>>> degrees = 45
>>> radians = degrees / 180.0 * [Link]
>>> [Link](radians)
0.707106781187
• If you know trigonometry, you can check the previous result by comparing it
to the square root of two, divided by two:
>>> [Link](2) / 2.0
0.707106781187
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 7
3.3 Composition
• One of the most useful features of programming languages is their
ability to take small building blocks and compose them. For example:
• The argument of a function can be
any kind of expression, including x = [Link](degrees / 360.0 * 2 * [Link])
arithmetic operators:
• And even function calls: x = [Link]([Link](x+1))
• Almost anywhere you can put a value, you can put an arbitrary expression,
with one exception: the left side of an assignment statement has to be a
variable name.
• Any other expression on the left >>> minutes = hours * 60 # right
side is a syntax error (there are >>> hours * 60 = minutes # wrong!
exceptions to this rule later). SyntaxError: can't assign to operator
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 8
4
13/09/2024
3.4 Adding new functions
• A function definition specifies the name of a new function and the sequence
of statements that run when the function is called.
• def is a keyword that indicates that def print_lyrics():
this is a function definition. The name print("I'm a lumberjack, and I'm okay.")
of the function is print_lyrics. print("I sleep all night and I work all day.")
• Function names follow identifiers' rules. Avoid having variables and functions with same name.
• The empty parentheses after the name indicate that this function doesn’t take any
arguments.
• The first line of the function definition is called the header; the rest is called the body.
• The header has to end with a colon and the body has to be indented.
• The body can contain any number of statements.
• The strings in the print statements are enclosed in double quotes.
• Single quotes and double quotes do the same thing.
• All quotation marks (single and double) must be "straight quotes". “Curly quotes” are not legal.
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 9
3.4 Adding new functions
• If you type a function definition in interactive mode, the interpreter
prints dots (...) to let you know that the definition isn’t complete:
• To end the function, you have >>> def print_lyrics():
to enter an empty line. ... print("I'm a lumberjack, and I'm okay.")
... print("I sleep all night and I work all day.")
...
• Defining a function creates a
>>> print(print_lyrics)
function object, which has type <function print_lyrics at 0xb7e99e9c>
function: >>> type(print_lyrics)
<class 'function'>
• The syntax for calling the new >>> print_lyrics()
function is the same as for I'm a lumberjack, and I'm okay.
built-in functions: I sleep all night and I work all day.
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 10
10
5
13/09/2024
3.4 Adding new functions
• Once you have defined a function, you can use it inside another
function.
• For example:
• To repeat the previous refrain, we def repeat_lyrics():
we could write a function called print_lyrics()
repeat_lyrics: print_lyrics()
• And then call repeat_lyrics: >>> repeat_lyrics()
• But that’s not really how the song goes. I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
I'm a lumberjack, and I'm okay.
I sleep all night and I work all day.
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 11
11
3.5 Definitions and uses
• Pulling together the code fragments from the previous section, the
whole program looks like this:
• It contains two function definitions: print_lyrics and repeat_lyrics.
• Function definitions get executed def print_lyrics():
just like other statements, but the print("I'm a lumberjack, and I'm okay.")
effect is to create function objects. print("I sleep all night and I work all day.")
• The statements inside the
function do not run until the def repeat_lyrics():
function is called, and the print_lyrics()
function definition generates no print_lyrics()
output.
repeat_lyrics()
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 12
12
6
13/09/2024
3.5 Definitions and uses
• You have to create a function before you can run it. In other words,
the function definition has to run before the function gets called.
• What happens if you move the last
def print_lyrics():
line of this program to the top, so
print("I'm a lumberjack, and I'm okay.")
the function call appears before the print("I sleep all night and I work all day.")
definitions?
• Now move the function call back to def repeat_lyrics():
the bottom and move the definition print_lyrics()
of print_lyrics after the definition of print_lyrics()
repeat_lyrics. What happens when
repeat_lyrics()
you run this program?
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 13
13
3.6 Flow of execution
• To ensure that a function is defined before its first use, you have to
know the order statements run in, which is called the flow of
execution.
• Execution always begins at the first statement of the program. Statements are
run one at a time, in order from top to bottom.
• Function definitions do not alter the flow of execution of the program but
remember that statements inside the function don’t run until the function is
called.
• A function call is like a detour in the flow of execution. Instead of going to the
next statement, the flow jumps to the body of the function, runs the
statements there, and then comes back to pick up where it left off.
• In summary, when you read a program, you don’t always want to read
from top to bottom.
• Sometimes it makes more sense if you follow the flow of execution.
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 14
14
7
13/09/2024
3.7 Parameters and arguments
• Some of the functions we have seen require arguments.
• For example, [Link] takes a number as an argument, while [Link] takes
two, the base and the exponent.
• Inside the function, the arguments are assigned to variables called parameters.
• Here is a definition for a function that takes an argument:
• This function assigns the argument to a parameter def print_twice(bruce):
named bruce. When the function is called, it prints print(bruce)
the value of the parameter (whatever it is) twice. print(bruce)
• This function works with any value that can be printed.
>>> print_twice('Spam') >>> print_twice(42) >>> print_twice([Link])
Spam 42 3.14159265359
Spam 42 3.14159265359
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 15
15
3.7 Parameters and arguments
• The same rules of composition that apply to built-in functions also apply to
programmer defined functions.
• We can use any kind of expression as an >>> print_twice([Link]([Link]))
argument for print_twice. -1.0
• The argument is evaluated before the function -1.0
is called. The expressions [Link]([Link]) >>> print_twice('Spam '*4)
and 'Spam ‘*4 are only evaluated once. Spam Spam Spam Spam
Spam Spam Spam Spam
• You can also use a variable as an argument:
• The name of the variable we pass as an >>> michael = 'Eric, the half a bee.'
argument (michael) has nothing to do with
>>> print_twice(michael)
the name of the parameter (bruce).
Eric, the half a bee.
• It doesn’t matter what the value was called
back home (in the caller); here in print_twice, Eric, the half a bee.
we call everybody bruce.
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 16
16
8
13/09/2024
3.8 Variables and parameters are local
• When you create a variable inside a function, it is local, which means that
it only exists inside the function. For example:
• This function takes two arguments, def cat_twice(part1, part2):
concatenates them and prints the cat = part1 + part2
result twice. print_twice(cat)
• Here is an example that uses it. When >>> line1 = 'Bing tiddle '
cat_twice terminates, the variable cat is >>> line2 = 'tiddle bang.'
destroyed. >>> cat_twice(line1, line2)
Bing tiddle tiddle bang.
Bing tiddle tiddle bang.
• If we try to print it, we get an exception:
>>> print(cat)
NameError: name 'cat' is not defined
• Parameters are also local.
• For example, outside print_twice, there is no such thing as bruce.
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 17
17
3.9 Stack diagrams
• To track which variables can be used where, we draw a stack diagram.
• Like state diagrams, stack diagrams show the value of each variable, but they
also show the function each variable belongs to.
• Each function is represented by a frame. A frame is a box with the name of a
function beside it and the parameters and variables of the function inside it.
• The frames are arranged in a stack that indicates which function called which,
and so on.
• In this example, print_twice was called by cat_twice,
and cat_twice was called by __main__, which is a
special name for the topmost frame.
• When you create a variable outside of any function,
it belongs to __main__.
• Each parameter refers to the same value as its
corresponding argument.
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 18
18
9
13/09/2024
3.9 Stack diagrams
• If an error occurs during a function call, Python prints the name of the
function, the name of the function that called it, and the name of the
function that called that, all the way back to __main__.
• For example, if you try to access cat from Traceback (innermost last):
within print_twice, you get a NameError: File "[Link]", line 13, in __main__
• This list of functions is called a traceback. cat_twice(line1, line2)
It tells you what program file the error File "[Link]", line 5, in cat_twice
occurred in, and what line, and what print_twice(cat)
functions were executing at the time. File "[Link]", line 9, in print_twice
• It also shows the line of code that caused print(cat)
the error. NameError: name 'cat' is not defined
• The order of the functions in the traceback is the same as the order of the
frames in the stack diagram. The function that is currently running is at the
bottom.
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 19
19
3.10 Fruitful functions and void functions
• Functions that return results are called fruitful functions. Others that
perform an action but don’t return a value are called void functions.
• When you call a fruitful function, you almost always want to do
something with the result;
• For example, you might assign it to a variable x = [Link](radians)
or use it as part of an expression: golden = ([Link](5) + 1) / 2
• When you call a function in interactive mode, >>> [Link](5)
Python displays the result: 2.2360679774997898
• But in a script, if you call a fruitful function all [Link](5)
by itself, the return value is lost forever!
This script computes the square root of 5, but since it does not store or
display the result; it is not very useful.
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 20
20
10
13/09/2024
3.10 Fruitful functions and void functions
• Void functions might display something on the screen or have some
other effect, but they don’t have a return value.
>>> result = print_twice('Bing')
Bing If you assign the result to a variable, you get a
Bing special value called None.
>>> print(result)
None
• The value None is not the same as the string 'None'.
• It is a special value that has its own type:
>>> type(None)
<class 'NoneType’>
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 21
21
3.11 Why functions?
• It may not be clear why it is worth the trouble to divide a program
into functions. There are several reasons:
• Creating a new function gives you an opportunity to name a group of
statements, which makes your program easier to read and debug.
• Functions can make a program smaller by eliminating repetitive code. Later, if
you make a change, you only have to make it in one place.
• Dividing a long program into functions allows you to debug the parts one at a
time and then assemble them into a working whole.
• Well-designed functions are often useful for many programs. Once you write
and debug one, you can reuse it.
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 22
22
11
13/09/2024
3.12 Debugging
• One of the most important skills you will acquire is debugging.
• Although it can be frustrating, debugging is one of the most intellectually rich,
challenging, and interesting parts of programming.
• In some ways debugging is like detective work. But it is also like an
experimental science.
• For some people, programming and debugging are the same thing.
• That is, programming is the process of gradually debugging a program until it
does what you want.
• The idea is that you should start with a working program and make small
modifications, debugging them as you go.
Think Python: How to Think Like a Computer Scientist (2nd) by Allen B. Downey 23
23
12