\chapter{Functions: part 1}
\label{lec-functions-1}
\section{Composing expressions}

So far, we have looked at the elements of a program---variables,
expressions, and statements---in isolation, without talking about how
to combine them. One of the most useful features of programming
languages is their ability to take small building blocks and
\myidx{compose} them. For example, we know how to add numbers and we
know how to print; it turns out we can do both at the same time:

\begin{pythonInteractive}
>>>  print 17 + 3
20
\end{pythonInteractive}

In reality, the addition has to happen before the printing, so the
actions aren't actually happening at the same time. The point is that
any expression involving numbers, strings, and variables can be used
inside a print statement. You've already seen an example of this:

\begin{python}
print "Number of minutes since midnight: ", hour * 60 + minute
\end{python}

You can also put arbitrary expressions on the right-hand side of an
assignment statement:

\begin{python}
percentage = (minute * 100) / 60
\end{python}

This ability may not seem impressive now, but you will see other
examples where composition makes it possible to express complex
computations neatly and concisely.

\textbf{Warning:} There are limits on where you can use certain
expressions. For example, the left-hand side of an assignment
statement has to be a \emph{variable} name, not an expression. So, the
following is illegal: \pythoninline{minute+1 = hour}.


\section{Function definitions and use}

In the context of programming, a \myidx{function} is a named sequence
of statements that performs a desired operation. This operation is
specified in a \myidx{function definition}. In Python, the syntax
for a function definition is:

\begin{python}
def NAME( LIST OF PARAMETERS ):
    STATEMENTS
\end{python}

You can make up any names you want for the functions you create,
except that you can't use a name that is a Python keyword. The list of
parameters specifies what information, if any, you have to provide in
order to use the new function.

There can be any number of statements inside the function, but they
have to be indented from the \pythoninline{def}. In the examples in
this book, we will use the standard indentation of four spaces. IDLE
automatically indents compound statements for you. Function
definitions are the first of several \myidx{compound statements} we
will see, all of which have the same pattern:
\begin{enumerate}
\item A \myidx{header}, which begins with a keyword and ends with a
  colon.
\item A \myidx{body} consisting of one or more Python statements, each
  indented the same amount -- \emph{4 spaces is the Python standard}
  -- from the header.

\end{enumerate}

In a function definition, the keyword in the header is
\pythoninline{def}, which is followed by the name of the function and
a list of \emph{parameters} enclosed in parentheses. The parameter
list may be empty, or it may contain any number of parameters. In
either case, the parentheses are required. The first couple of
functions we are going to write have no parameters, so the syntax
looks like this:

\begin{python}
def new_line():
    print
\end{python}

This function is named \pythoninline{new\_line}. The empty parentheses
indicate that it has no parameters. Its body contains only a single
statement, which outputs a newline character. (That's what happens
when you use a print command without any arguments.)

Defining a new function does not make the function run. To do that we
need a \myidx{function call}. Function calls contain the name of the
function being executed followed by a list of values, called
\emph{arguments}, which are assigned to the parameters in the
function definition. Our first examples have an empty parameter list,
so the function calls do not take any arguments. Notice, however, that
the \emph{parentheses are required in the function call} :

\begin{python}
print "First Line."
new_line()
print "Second Line."
\end{python}

The output of this program is:
\begin{pythonOutput}

First line.

Second line.

\end{pythonOutput}

The extra space between the two lines is a result of the
\pythoninline{new\_line()}
function call. What if we wanted more space between the lines? We
could call the same function repeatedly:

\begin{python}
print "First Line."
new_line()
new_line()
new_line()
print "Second Line."
\end{python}

Or we could write a new function named \pythoninline{three\_lines} that
prints three new lines:

\begin{python}
def three_lines():
    new_line()
    new_line()
    new_line()

print "First Line."
three_lines()
print "Second Line."
\end{python}

This function contains three statements, all of which are indented by
four spaces. Since the next statement is not indented, Python knows
that it is not part of the function. You should notice a few things
about this program:
\begin{itemize}
\item You can call the same procedure repeatedly. In fact, it is quite
  common and useful to do so.
\item You can have one function call another function; in this case
  \pythoninline{three\_lines} calls \pythoninline{new\_line}.
\end{itemize}

So far, it may not be clear why it is worth the trouble to create all
of these new functions. Actually, there are a lot of reasons, but this
example demonstrates two:
\begin{enumerate}
\item Creating a new function gives you an opportunity to name a group
of statements. Functions can simplify a program by hiding a complex
computation behind a single command and by using English words in
place of arcane code.
\item Creating a new function can make a program smaller by
eliminating repetitive code. For example, a short way to print nine
consecutive new lines is to call \pythoninline{three\_lines} three times.
\end{enumerate}

Pulling together the code fragments from the previous section into a
script named \myurl{functions.py}, the whole program looks like this:

\begin{python}
def new_line():
    print

def three_lines():
    new_line()
    new_line()
    new_line()

print "First Line."
three_lines()
print "Second Line."
\end{python}

This program contains two function definitions:
\pythoninline{new\_line} and \pythoninline{three\_lines}. Function
definitions get executed just like other statements, but the effect is
to create the new function. The statements inside the function do not
get executed until the function is called, and the function definition
generates no output.  As you might expect, you have to create a
function before you can execute it. In other words, the function
definition has to be executed before the first time it is called.

\section{Flow of execution}

In order to ensure that a function is defined before its first use,
you have to know the order in which statements are executed, which is
called the \myidx{flow of execution}. Execution always begins at the
first statement of the program. Statements are executed 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 are not executed until the function is called. Although
it is not common, you can define one function inside another. In this
case, the inner definition isn't executed until the outer function is
called.

Function calls are like a detour in the flow of execution. Instead of
going to the next statement, the flow jumps to the first line of the
called function, executes all the statements there, and then comes
back to pick up where it left off. That sounds simple enough, until
you remember that one function can call another. While in the middle
of one function, the program might have to execute the statements in
another function. But while executing that new function, the program
might have to execute yet another function! Fortunately, Python is
adept at keeping track of where it is, so each time a function
completes, the program picks up where it left off in the function that
called it. When it gets to the end of the program, it terminates.


What's the moral of this sordid tale? When you read a program, don't
read from top to bottom. Instead, follow the flow of execution.

\section{Parameters and arguments}

Most functions require arguments, values that control how the function
does its job. For example, if you want to find the absolute value of a
number, you have to indicate what the number is. Python has a built-in
function for computing the absolute value:

\begin{pythonInteractive}
>>> abs(5)
5
>>> abs(-5)
5
\end{pythonInteractive}

In this example, the arguments to the \pythoninline{abs} function are
\pythoninline{5} and \pythoninline{-5}.

Some functions take more than one argument. For example the built-in
function \pythoninline{pow} takes two arguments, the base and the
exponent. Inside the function, the values that are passed get assigned
to variables called \myidx{parameters}.

\begin{pythonInteractive}
>>> pow(2, 3)
8
>>> pow(7, 4)
2401
\end{pythonInteractive}

Another built-in function that takes more than one argument is
\pythoninline{max}.
\begin{pythonInteractive}
>>> max(7, 11)
11
>>> max(4, 1, 17, 2, 12)
17
>>> max(3*11, 5**3, 512-9, 1024**0)
503
\end{pythonInteractive}


The function \pythoninline{max} can be sent any number of arguments,
separated by commas, and will return the maximum value sent. The
arguments can be either simple values or expressions. In the last
example, \pythoninline{503} is returned, since it is larger than
\pythoninline{33}, \pythoninline{125}, and \pythoninline{1}.

\newpage
Here is an example of a user-defined function that has a parameter:
\begin{python}
def print_twice(bruce):
    print bruce, bruce
\end{python}

This function takes a single \myidx{argument} and assigns it to the
parameter named \pythoninline{bruce}. The value of the parameter (at
this point we have no idea what it will be) is printed twice, followed
by a newline. The name \pythoninline{bruce} was chosen to suggest that
the name you give a parameter is up to you, but in general, you want
to choose something more illustrative than \pythoninline{bruce}.

% this bit is out of place here - no need for it at this stage
% The interactive Python shell provides us with a convenient way to test
% our functions. We can use the \myidx{\pythoninline{import} statement}
% to bring the functions we have defined in a script into the
% interpreter session. To see how this works, assume the
% \pythoninline{print_twice} function is defined in a script named
% \texttt{chap03.py}. We can now test it interactively by
% \emph{importing} it into our Python shell session:
% \begin{python}
% >>> from chap03 import *
% >>> print_twice('Spam')
% Spam Spam
% >>> print_twice(5)
% 5 5
% >>> print_twice(3.14159)
% 3.14159 3.14159
% \end{python}

In a function call, the value of the argument is assigned to the
corresponding parameter in the function definition. In effect, it is
as if \pythoninline{bruce = 'Spam'} is executed when
\pythoninline{print\_twice('Spam')} is called;
\pythoninline{bruce = 5} is executed when
\pythoninline{print\_twice(5)} is called; and
\pythoninline{bruce = 3.14159} is executed when
\pythoninline{print\_twice(3.14159)} is called.
Any type of argument that can be printed can be sent to
\pythoninline{print\_twice}. In the first function call, the argument
is a string. In the second, it's an integer. In the third, it's a float.

As with built-in functions, we can use an expression as an argument
for \pythoninline{print\_twice}:
\begin{python}
>>> print_twice('Spam'*4)
SpamSpamSpamSpam SpamSpamSpamSpam
\end{python}

\pythoninline{'Spam'*4} is first evaluated to
'\pythoninline{SpamSpamSpamSpam}', which is then passed as an argument
to \pythoninline{print\_twice}.

\section{Function composition}

Just as with mathematical functions, Python functions can be
\myidx{composed}, meaning that you use the result of one function as
the input to another.
\begin{pythonInteractive}
>>> print_twice(abs(-7))
7 7
>>> print_twice(max(3, 1, abs(-11), 7))
11 11
\end{pythonInteractive}

In the first example, \pythoninline{abs(-7)} evaluates to
\pythoninline{7}, which then becomes the
argument to \pythoninline{print\_twice}. In the second example we have
two levels of composition, since \pythoninline{abs(-11)} is first
evaluated to \pythoninline{11} before \pythoninline{max(3, 1, 11, 7)}
is evaluated to \pythoninline{11} and \pythoninline{print\_twice(11)}
then displays the result.

We can also use a variable as an argument:
\begin{python}
>>> michael = 'Eric, the half a bee.'
>>> print_twice(michael)
Eric, the half a bee. Eric, the half a bee.
\end{python}

Notice something very important here. The name of the variable we pass
as an argument (\pythoninline{michael}) has nothing to do with the
name of the parameter (\pythoninline{bruce}). It doesn't matter what
the value was called back home (in the caller); here in
\pythoninline{print\_twice}, we call everybody \pythoninline{bruce}.


\section{Glossary}
\begin{description}
\item[function:]A named sequence of statements that performs some
useful operation. Functions may or may not take parameters and may
or may not produce a result.
\item[function definition:]A statement that creates a new function,
specifying its name, parameters, and the statements it executes.
\item[compound statement:]A statement that consists of two
parts: 
\begin{enumerate}
\item header - which begins with a keyword determining the statement
type, and ends with a colon.
\item body - containing one or more statements indented the same
amount from the header.
\end{enumerate}
The syntax of a compound statement looks like this:
\begin{python}
keyword expression :
    statement
    statement ...
\end{python}

\item[header:]The first part of a compound statement. Headers begin
  with a keyword and end with a colon (\pythoninline{:})
\item[body:]The second part of a compound statement. The body consists
  of a sequence of statements all indented the same amount from the
  beginning of the header. The standard amount of indentation used
  within the Python community is 4 spaces.
\item[flow of execution:]The order in which statements are executed
  during a program run.
\item[parameter:]A name used inside a function to refer to the value
  passed as an argument.
\item[argument:]A value provided to a function when the function is
  called. This value is assigned to the corresponding parameter in the
  function.

\item[abs function:]Returns the absolute value of the argument.
\item[pow function:]Returns the first argument raised to the power of
  the second one, equivalent to \pythoninline{x**y}.
\item[max function:]Returns the largest argument (if given more than
  one), or the largest item in a sequence (if given a single
  sequence).
\begin{python}
>>> max(3, 8, 2, 1)
8
>>> max([2, 0, 9, 4])
9
\end{python}
% import stuff to be done in a later lecture
% \item[import:]

% A statement which permits functions and variables defined in a
% Python script to be brought into the environment of another script
% or a running Python shell.
%   For example, assume the following is in a script named tryme.py:
% \begin{python}
% def print_thrice(thing):
%     print thing, thing, thing

% n = 42
% s = "And now for something completely different..."
% \end{python}

% Now begin a python shell from within the same directory where
% tryme.py is located:
% \begin{python}
% $ ls
% tryme.py  <and other stuff...>
% $ python
% >>>

% \end{python}

% Three names are defined in tryme.py: \pythoninline{print\_thrice},
% \pythoninline{n}, and \pythoninline{s}. If we 
% try to access any of these in the shell without first importing, we
% get an error:
% \begin{pythonOutput}
% >>> n
% Traceback (most recent call last):
%   File "<stdin>", line 1, in <module>
% NameError: name 'n' is not defined
% >>> print_thrice("ouch!")
% Traceback (most recent call last):
%   File "<stdin>", line 1, in <module>
% NameError: name 'print_thrice' is not defined
% \end{pythonOutput}

% If we import everything from tryme.py, however, we can use
% everything defined in it:
% \begin{pythonInteractive}
% >>> from tryme import *
% >>> n
% 42
% >>> s
% 'And now for something completely different...'
% >>> print_thrice("Yipee!")
% Yipee! Yipee! Yipee!
% >>>
% \end{pythonInteractive}

% Note that you do not include the .py from the script name in the
% import statement.

\item[function composition:]Using the output from one function call as
  the input to another.

\end{description}

\section{Laboratory exercises}
\begin{enumerate}
\item Using IDLE, create a Python script named
  \myurl{functions.py}.  Type the definition of the function
  \pythoninline{new\_line} from the lecture at the top of the file,
  and then add the definition of the function
  \pythoninline{three\_lines} below it.  Run the program (it won't
  seem to do anything), and then change to the interpreter window and
  call \pythoninline{three\_lines} to check that it works as expected.

\item Add a function to the file called \pythoninline{nine\_lines} that
  uses \pythoninline{three\_lines} to print nine blank lines. Now add
  a function named \pythoninline{clear\_screen} that prints out
  forty blank lines.  The last line of your program should be a
  \emph{call} to \pythoninline{clear\_screen}.
\item Move the last line of \myurl{functions.py} to the top of the
  program, so the \emph{function call} to \pythoninline{clear\_screen}
  appears before the \emph{function definition}. Run the program and
  record the error message you get.
\begin{answerspace}

zend
\end{answerspace}

\item State a rule about \emph{function definitions} and \emph{function
  calls} which describes where they can appear relative to each other
in a program?
\begin{answerspace}

zend
\end{answerspace}

\item Starting with a working version of \myurl{functions.py},
  move the definition of \pythoninline{new\_line} after the definition
  of \pythoninline{three\_lines}. Record what happens when you run
  this program. Now move the definition of \pythoninline{new\_line}
  below a call to \pythoninline{three\_lines()}.  Explain how this is
  an example of the rule you stated in the previous exercise.
\begin{answerspace}

zend
\end{answerspace}

\item One of the reasons functions are useful is that they help to
  avoid needless repetition.  Instead of using copy and paste to
  duplicate the same lines of code many times in a program, we wrap the
  lines we want in a function and then call that function whenever we
  need to.  Avoiding repetition also means we don't have to type the
  same commands over and over again.  Let's say we have a list of
  numbers and we want to print out some information about it.

\begin{python}
>>> nums = [4, 9, 3, 17, 21, 6, 14]
>>> min(nums)
3
>>> max(nums)
21
>>> sum(nums)
74
>>> float(sum(nums))/len(nums)
10.571428571428571
\end{python}

The only new function here is \pythoninline{sum} which (not
surprisingly) returns the sum of a list of numbers.

If we were regularly printing out this information for different lists
of numbers it would be sensible to define a function which printed out a
summary of what we wanted to know.  Write a function which when called
like this \pythoninline{info(nums)} prints out something like this:
\begin{pythonOutput}
Min: 3, Max: 21, Sum: 74, Average: 10.571428571428571
\end{pythonOutput}

\item Try to complete up to level seven on the game you played in the
  previous labs.
  % 6: need to use functions, 7: repeated functions

% this question is bizarre - students have not yet met loops,
 % conditionals or even jump statements, so it seems as this question
 % is impossible to complete given their current knowledge. Is this
 % intended? Anyway, I think we can ignore it.
% \item
% Fill in the \emph{body} of the \emph{function definition} for
% \pythoninline{cat\_n\_times} so that it will print the string, s, n times:
% \begin{python}
% def cat_n_times(s, n):
%     <fill in your code here>
% \end{python}

% Save this function in a script named import\_test.py. Now at a unix
% prompt, make sure you are in the same directory where the
% import\_test.py is located (ls should show import\_test.py). Start a
% Python shell and try the following:

% \begin{python}
% >>> from import_test import *
% >>> cat_n_times('Spam', 7)
% SpamSpamSpamSpamSpamSpamSpam
% \end{python}

% If all is well, your session should work the same as this one. 
% Experiment with other calls to \pythoninline{cat\_n\_times} until you
% feel comfortable with how it works.

\end{enumerate}

\submitreminder
