\chapter{Python built-ins (batteries included)}

Many common tasks come up time and time again when programming. 
Instead of requiring you to constantly reinvent the wheel, Python has
a number of built-in features which you can use. Including so much
ready to use code in Python is sometimes referred to as a 'batteries
included' philosophy. Python comes with just under fifty predefined
functions (of which we'll be using only about a dozen) and the
simplest way to use this prewritten code is via function
calls.\footnote{Not everything that appears to be a function call
actually is, but you don't need to worry about that in this course. 
For the sake of simplicity we'll say that everything that looks like a
function is a function.}

\section{Function calls}

The syntax of a function call is simply

\pythoninline{ FUNCTIONNAME(ARGUMENTS)}

Not all functions take an argument, and some take more than one
(in which case they are separated by commas).

You have already seen an example of a \myidx{function call}:
\begin{pythonInteractive}
>>> type("Hello, World!")
<type 'str'>
>>> type(17)
<type 'int'>
\end{pythonInteractive}

The name of the function is \pythoninline{type}, and it displays the
type of a value or variable.  The value or variable, which is called
the \myidx{argument} of the function, has to be enclosed in
parentheses.  It is common to say that a function ``takes'' an
argument and ``returns'' a result.  The result is called the
\myidx{return value}.

Instead of printing the return value we could assign it to a variable:

\begin{pythonInteractive}
>>> result = type(17)
>>> print result
<type 'int'>
\end{pythonInteractive}

Another useful function is \myidx{len}.  It takes a sequence as an
argument and returns its length.  For a string this is the number of
characters it contains.

\begin{pythonInteractive}
>>> my_str = 'Hello world'
>>> len(my_str)
11
\end{pythonInteractive}

The \pythoninline{len} function can only be used on sequences.  Trying
to use it on a number, for example, results in an error.

\begin{pythonInteractive}
>>> len(3)
TypeError: object of type 'int' has no len()
\end{pythonInteractive}
 

\section{Type conversion}
\label{sec-type-conversion}

Each Python type comes with a built-in function that attempts to
convert values of another type into that type. The
\pythoninline{int(ARGUMENT)} function, for example, takes any value
and converts it to an integer, if possible, or complains otherwise:
\begin{pythonInteractive}
>>> int("32")
32
>>> int("Hello")
ValueError: invalid literal for int() with base 10: 'Hello'
\end{pythonInteractive}
The \pythoninline{int} function can also convert floating-point values
to integers, but note that it truncates the fractional part:
\begin{pythonInteractive}
>>> int(-2.3)
-2
>>> int(3.99999)
3
>>> int("42")
42
>>> int(1.0)
1
\end{pythonInteractive}

The \pythoninline{float(ARGUMENT)} function converts integers and
strings to floating-point numbers:
\begin{pythonInteractive}
>>> float(32)
32.0
>>> float("3.14159")
3.14159
>>> float(1)
1.0
\end{pythonInteractive}
It may seem odd that Python distinguishes the integer value
\pythoninline{1} from the floating-point value \pythoninline{1.0}.
They may represent the same number, but they belong to different
types. The reason is that they are represented differently inside the
computer. 

\newpage
The \pythoninline{str(ARGUMENT)} function converts any argument given
to it to type string:
\begin{pythonInteractive}
>>> str(32)
'32'
>>> str(3.14149)
'3.14149'
>>> str(True)
'True'
>>> str(true)
NameError: name 'true' is not defined
\end{pythonInteractive}
The \pythoninline{str(ARGUMENT)} function will work with any value and
convert it into a string.  Note: \pythoninline{True} is a
predefined value in Python; true is not. We will see more of
\pythoninline{True} in lecture \ref{lecture-conditionals}.

\section{Input}
\label{sec-input}

Remember at the start of the course we said that programs are made up
of instructions which only perform a handful of
operations\footnote{See the list back on
  page~\pageref{basic-instructions} to refresh your memory.}.  The
first two of these operations were input and output.  Input involves
getting data from the keyboard, a file, or some other device.  
Output is concerned with displaying data on the screen or sending data
to a file or other device.

So we have done quite a bit of displaying data on the screen using the
\pythoninline{print} command, which fits into the category of output.
We are now going to look at one of the most basic input tasks: getting
keyboard input.

There are two built-in functions in Python for getting keyboard input,
\pythoninline{input} and \pythoninline{raw\_input}:

\begin{python}
name = raw_input("Please enter your name: ")
print name
num = input("Enter a numerical expression: ")
print num
\end{python}

A sample run of this script would look something like this:

\begin{shell}
$ python tryinput.py
Please enter your name: Arthur, King of the Britons
Arthur, King of the Britons
Enter a numerical expression: 7 * 3
21
\end{shell} % $ (keep emacs happy)

Each of these functions allows a \emph{prompt} to be given as an
argument to the function between the parentheses.  The result returned
by \pythoninline{raw\_input} is always a string.  But the result
returned from \pythoninline{input} can be any valid Python type.

\newpage
\begin{pythonInteractive}
>>> n = raw_input()
hello
>>> n
'hello'
>>> type(n)
<type 'str'>
>>> n = input()
1.5 + 2
>>> n
3.5
>>> type(n)
<type 'float'>
\end{pythonInteractive}


\section{Methods}

In addition to the functions which we have seen so far there is also a
special type of function which we call a method.  You can think of a
method as a function which is attached to a certain type of variable
(e.g. a string).

When calling a function you just need the name of the function
followed by parentheses (possibly with some arguments inside).  In
contrast a method also needs a variable (also called an object) to be
called upon.  The syntax that is used is the variable (or object) name
followed by a dot followed by the name of the method along with
possibly some arguments in parentheses like this:

\pythoninline{ VARIABLE.METHODNAME(ARGUMENTS)}

You can see that it looks just like a function call except for the
variable name and the dot at the start.
Compare how the \pythoninline{len} function and
the \pythoninline{upper} method are used below.

\begin{pythonInteractive}
>>> my_str = 'hello world'
>>> len(my_str)
11
>>> my_str.upper()
'HELLO WORLD'
\end{pythonInteractive}

The \pythoninline{len} function returns the length of the sequence
which is given as an argument.  The \pythoninline{upper} method
returns a new string which is the same as the string that it is called
upon except that each character has been converted to uppercase.  In
each case the original string remains unchanged.

An example of a method which needs an argument to operate on 
is the \pythoninline{count} method.

\begin{pythonInteractive}
>>> my_str = 'the quick brown fox jumps over the lazy dog.'
>>> my_str.count('the')
2
>>> my_str.count('hello')
0
>>> my_str.count('e')
3
\end{pythonInteractive}

\newpage
The count method returns the number of times the string given as an
argument occurs within the string that it is called upon. But what
about the following:
\begin{pythonInteractive}
>>> ms = "ahaha"
>>> ms.count("aha")
\end{pythonInteractive}

\section{Examining things}

A good way to examine a type, to see what methods are available, is by
using the \pythoninline{dir} function.  Here we use
\pythoninline{dir} on \pythoninline{str} (the string type).

\begin{pythonInteractive}
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__',
'__eq__', '__ge__', '__getattribute__', '__getitem__',
'__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__',
'__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__',
'__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__',
'__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count',
'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index',
'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle',
'isupper', 'join', 'ljust', 'lower', 'lstrip', 'partition', 'replace',
'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split',
'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate',
'upper', 'zfill']
\end{pythonInteractive}

This returns a list containing the names of all of the methods that
can be called on a given type of object.  A list starts with an
opening bracket, ends with a closing bracket, and contains items which
are separated by commas.  Each item in the above list is a string.
Don't worry about all of the ones at the start which begin and end
with two underscores, we will touch on some of them later in the
course.  For now just look at the other method names which are in this
list.  The two string methods which we have used so far, \emph{count}
and \emph{upper}, are both there.  You can get more detailed
information about all of these methods using the \pythoninline{help}
function.

\begin{pythonInteractive}
>>> help(str)
\end{pythonInteractive}

Try entering the above command which will open the online help system
to examine the string type.  You can scroll up and down with the arrow
keys or space bar.  Press q to exit the help screen.

You can just get help on a particular method,
e.g. \pythoninline{upper}, like so:
\begin{pythonInteractive}
>>> help(str.upper)
\end{pythonInteractive}

You can enter the online help utility, which contains all sorts of
information, by using the \pythoninline{help} function without giving
it any arguments.

\begin{pythonInteractive}
>>> help()
\end{pythonInteractive}

\section{More types}

Python has a number of built-in types, in addition to those which you
have already seen, which are simple to create and manipulate.
Table~\ref{table:built-in-types} lists Python's most commonly used
built-in types.

\begin{table}[h]
\centering
\begin{tabular}{|l|l|} \hline
  Type & Examples \\ \hline
  Boolean & \verb|passed = True, finished = False|\\
  Dictionary & \verb|extns = {'Brendan': 8588, 'Nick': 5242, 'Iain': 8584}|\\
  File & \verb|somefile = open('input.txt')|\\
  Float & \verb|pi = 3.14, average = -87.333333|\\
  Int & \verb|age = 21, height = 167|\\
  List & \verb|oddnums = [1, 3, 5, 'seven', 9]|\\
  String & \verb|breakfast = "weetbix", lunch = 'filled roll'|\\
  Tuple & \verb|even_nums = (2, 'four', 6, 8)|\\ 
  \hline
\end{tabular}
\caption{Built-in types}
\label{table:built-in-types}
\end{table}

Each of these types will be covered in more depth in later chapters,
but they are so useful that we will introduce some of their features
earlier on.  They make it possible to write simple programs fast.

\section{Strings and lists}

One of the most useful methods that you can use with strings is called
\pythoninline{split}.  It returns a list which is made by splitting
the string into individual words. By default, any block of consecutive
whitespace characters (space, tab or newline) is considered a word
boundary.

\begin{pythonInteractive}
>>> line = 'the large black cat sat on a large red mat'
>>> mylist = line.split()
>>> mylist
['the', 'large', 'black', 'cat', 'sat', 'on', 'a', 'large', 'red', 'mat']

\end{pythonInteractive}

That was pretty easy.  Now that we have a list containing each
individual word there are a number of things we might like to do with
it.  For example, we might like to count the number of times a given
word occurs in the list.  This is obviously trivial to do with a list
this small, but if our original string contained the entire contents
of a book having an automated way of doing it would save a lot of
time.  It turns out that lists have a \pythoninline{count} method
which will give us the number of times a given item is found in it.

\begin{pythonInteractive}
>>> mylist.count('cat')
1
>>> mylist.count('large')
2
>>> mylist.count('dog')
0
\end{pythonInteractive}

Another useful method which lists have is \pythoninline{sort}

\begin{pythonInteractive}
>>> mylist
['the', 'large', 'black', 'cat', 'sat', 'on', 'a', 'large', 'red', 'mat']
>>> mylist.sort()
>>> mylist
['a', 'black', 'cat', 'large', 'large', 'mat', 'on', 'red', 'sat', 'the']
\end{pythonInteractive}


\section{Glossary}
\begin{description}
\item[function call:]A statement that executes a function. It consists
  of the name of the function followed by a list of arguments enclosed
  in parentheses.
\item[arguments:]A comma separated list of values or variables which
  are placed between the parentheses of a function being called. 
\item[len function:]A function which returns the number of items in
  the sequence given as an argument.
\begin{python}
>>> len([2, 3, 5, 7])
4
\end{python}
\item[type conversion:]An explicit statement that takes a value of one
  type and computes a corresponding value of another type.
\item[int function:]Converts a string or number to an integer, if
  possible.
\begin{python}
>>> int("12")
12
\end{python}
\item[float function:]Converts a string or number to a floating point
  number, if possible.
\item[str function:]Returns a string representation of the given
  argument.
\item[raw\_input function:]Reads a string from standard input.  Takes an
  optional prompt argument.
\item[input function:]Reads a string from standard input, and attempts
  to evaluate it as python code.
\item[method:]A kind of function that uses a slightly different syntax
  and is called on an object.
\item[dir function:]Returns a list of the attributes (such as methods)
  of a given object.
\item[help function:]Shows information about the given argument.
\item[upper method:]Returns a copy of the string argument converted to
  uppercase.
\begin{python}
>>> my_str = "hello"
>>> my_str.upper()
'HELLO'
\end{python}
\item[count method:]A \pythoninline{list} method which returns the
  number of occurrences of the given argument.
\item[split method:]A method which returns a list of the words in the
  given string.
\item[sort method:]A method which sorts items contained in a list. 

\end{description}

\section{Laboratory exercises}

\begin{enumerate}

\item Can any type of variable be converted to any other type of
  variable in Python?  Explain why or why not.
\begin{answerspace}




zend
\end{answerspace}

\item The difference between \pythoninline{input} and
  \pythoninline{raw\_input} is that \pythoninline{input} evaluates the
  input string and \pythoninline{raw\_input} does not. Try the
  following in the interpreter and record what happens:

\begin{pythonInteractive}
>>> x = input()
3.14
>>> type(x)
\end{pythonInteractive}
\begin{answerspace}

zend
\end{answerspace}

\begin{pythonInteractive}
>>> x = raw_input()
3.14
>>> type(x)
\end{pythonInteractive}
\begin{answerspace}

zend
\end{answerspace}

\begin{pythonInteractive}
>>> x = input()
'The cat said "Meow!"'
>>> x
\end{pythonInteractive}
\begin{answerspace}

zend
\end{answerspace}


What happens if you try the example above without the quotation
marks?
\begin{pythonInteractive}
>>> x = input()
The cat said "Meow!"
>>> x
\end{pythonInteractive}
\begin{answerspace}

zend
\end{answerspace}

\begin{pythonInteractive}
>>> x = raw_input()
'The cat said "Meow!"'
>>> x
\end{pythonInteractive}
\begin{answerspace}

zend
\end{answerspace}

Describe and explain each result.


\item What is the difference between calling a function and a method?

\begin{answerspace}


zend
\end{answerspace}

\item What function returns a list of methods belonging to a given
  type?
\begin{answerspace}

zend
\end{answerspace}

\item What do the following string methods do?
  \begin{itemize}
    \item lower
\begin{answerspace}

zend
\end{answerspace}
    \item count
\begin{answerspace}

zend
\end{answerspace}

    \item replace
\begin{answerspace}

zend
\end{answerspace}

   \end{itemize}

\item What function do you use to get information about individual
  methods or all of the methods belonging to a type?
\begin{answerspace}

zend
\end{answerspace}

\item \emph{Extension Exercise:} Write instructions to perform each of
  the steps below in the space provided.
\begin{enumerate}
  \item Create a string containing at least five words and store it in
    a variable.
  \item Print out the string.
  \item Convert the string to a list of words using the string
    \pythoninline{split} method.
  \item Sort the list into reverse alphabetical order using some of
    the list methods (you might need to use \pythoninline{dir(list)}
    or \pythoninline{help(list)} to find appropriate methods).
  \item Print out the sorted, reversed list of words.
\end{enumerate}

\begin{answerspace}







zend
\end{answerspace}
Once you have written the statements in the space above, then type
them into a script and run it to check that it works.

\item If you have time, try to complete up to level five on the game you
  played during the previous lab.
  % 4: two-level jump, 5: jump up four

\end{enumerate}

\submitreminder
