span>Preliminaries
1.1 What is Python?
Python is a powerful modern computer programming language. It bears some similarities to
Fortran, one of the earliest programming languages, but it is much more powerful than Fortran.
Python allows you to use variables without declaring them (i.e., it determines types implicitly),
and it relies on indentation as a control structure. You are not forced to define classes in Python
(unlike Java) but you are free to do so when convenient.
Python was developed by Guido van Rossum, and it is free software. Free as in “free beer,” in that
you can obtain Python without spending any money. But Python is also free in other important
ways, for example you are free to copy it as many times as you like, and free to study the source
code, and make changes to it. There is a worldwide movement behind the idea of free software,
initiated in 1983 by Richard Stallman.1
This document focuses on learning Python for the purpose of doing mathematical calculations.
We assume the reader has some knowledge of basic mathematics, but we try not to assume any
previous exposure to computer programming, although some such exposure would certainly be
helpful. Python is a good choice for mathematical calculations, since we can write code quickly, test
it easily, and its syntax is similar to the way mathematical ideas are expressed in the mathematical
literature. By learning Python you will also be learning a major tool used by many web developers.
1.2 Installation and documentation
If you use Mac OS X or Linux, then Python should already be installed on your computer by
default. If not, you can download the latest version by visiting the Python home page, at
http://www.python.org
where you will also find loads of documentation and other useful information. Windows users can
also download Python at this website. Don’t forget this website; it is your first point of reference
for all things Python. You will find there, for example, reference [1], the excellent Python Tutorial
by Guido van Rossum. You may find it useful to read along in the Tutorial as a supplement to
this document.
2 Getting started
2.1 Running Python as a calculator
The easiest way to get started is to run Python as an interpreter, which behaves similar to the
way one would use a calculator. In the interpreter, you type a command, and Python produces
the answer. Then you type another command, which again produes an answer, and so on.
In OS X or Linux, to start the Python interpreter is as simple as typing the command python
on the command line in a terminal shell. In Windows, assuming that Python has already been
1See http://www.fsf.org or http://www.opensource.org for more information.
4
installed, you need to find Python in the appropriate menu. Windows users may choose to run
Python in a command shell (i.e., a DOS window) where it will behave very similarly to Linux or
OS X.
For all three operating systems (Linux, OS X, Windows) there is also an integrated development
environment for Python named IDLE. If interested, you may download and install this on your computer.2 For help on getting started with IDLE see http://hkn.eecs.berkeley.edu/~dyoo/python/idle_int
Once Python starts running in interpreter mode, using IDLE or a command shell, it produces a
prompt, which waits for your input. For example, this is what I get when I start Python in a
command shell on my Linux box:
doty@brauer:~% python
Python 2.5.2 ( r252 :60911 , Apr 21 2008 , 11:12:42)
[GCC 4.2.3 ( Ubuntu 4.2.3 -2ubuntu7)] on linux2
Type " help", " copyright", " credits" or " license" for more
information.
>>>
where the three symbols >>> indicates the prompt awaiting my input.
So experiment, using the Python interpreter as a calculator. Be assured that you cannot harm
anything, so play with Python as much as you like. For example:
>>> 2*1024
2048
>>> 3+4+9
16
>>> 2**100
1267650600228229401496703205376 L
In the above, we first asked for the product of 2 and 1024, then we asked for the sum of 3, 4, and 9
and finally we asked for the value of 2100. Note that multiplication in Python is represented by ∗,
addition by +, and exponents by **; you will need to remember this syntax. The L appended to
the last answer is there to indicate that this is a long integer; more on this later. It is also worth
noting that Python does arbitrary precision integer arithmetic, by default:
>>> 2**1000
107150860718626732094842504906000181056140481170553 3607443750
388370351051124936122493198378815695858127594672917 5531468251
871452856923140435984577574698574803934567774824230 9854210746
050623711418779541821530464749835819412673987675591 6554394607
706291457119647768654216766042983165262438683720566 8069376L
Here is another example, where we print a table of perfect squares:
>>> for n in [1 ,2 ,3 ,4 ,5 ,6]:
... print n **2
...
149
16
25
36
2Both Python and IDLE should be already preinstalled on all Loyola Windows computers.
5
This illustrates several points. First, the expression [1,2,3,4,5,6] is a list, and we print the values
of n2 for n varying over the list. If we prefer, we can print horizontally instead of vertically:
>>> for n in [1 ,2 ,3 ,4 ,5 ,6]:
... print n**2 ,
...
1 4 9 16 25 36
simply by adding a comma at the end of the print command, which tells Python not to move to
a new line before the next print.
These last two examples are examples of a compound command, where the command is divided
over two lines (or more). That is why you see ... on the second line instead of the usual >>>,
which is the interpreter’s way of telling us it awaits the rest of the command. On the third line
we entered nothing, in order to tell the interpreter that the command was complete at the second
line. Also notice the colon at the end of the first line, and the indentation in the second line. Both
are required in compound Python commands.
2.2 Quitting the interpreter
In a terminal you can quit a Python session by CTRL-D. (Hold down the CTRL key while pressing
the D key.) In IDLE you can also quit from the menu.
If the interpreter gets stuck in an infinite loop, you can quit the current execution by CTRL-C.
2.3 Loading commands from the library
Python has a very extensive library of commands, documented in the Python Library Reference
Manual [2]. These commands are organized into modules. One of the available modules is especially
useful for us: the math module. Let’s see how it may be used.
>>> from math import sqrt , exp
>>> exp( -1)
0.36787944117144233
>>> sqrt (2)
1.4142135623730951
We first import the sqrt and exp functions from the math module, then use them to compute
e−1 = 1/e and √2.
Once we have loaded a function from a module, it is available for the rest of that session. When
we start a new session, we have to reload the function if we need it.
Note that we could have loaded both functions sqrt and exp by using a wildcard *:
>>> from math import *
which tells Python to import all the functions in the math module.
What would have happened if we forgot to import a needed function? After starting a new session,
if we type
>>> sqrt (2)
Traceback ( most recent call last ):
File "<stdin >", line 1, in <module >
NameError: name ’sqrt ’ is not defined
6
we see an example of an error message, telling us that Python does not recognize sqrt.
2.4 Defining functions
It is possible, and very useful, to define our own functions in Python. Generally speaking, if you
need to do a calculation only once, then use the interpreter. But when you or others have need to
perform a certain type of calculation many times, then define a function. For a simple example,
the compound command
>>> def f(x):
... return x*x
...
defines the squaring function f(x) = x2, a popular example used in elementary math courses. In
the definition, the first line is the function header where the name, f, of the function is specified.
Subsequent lines give the body of the function, where the output value is calculated. Note that
the final step is to return the answer; without it we would never see any results. Continuing the
example, we can use the function to calculate the square of any given input:
>>> f(2)
4
>>> f (2.5)
6.25
The name of a function is purely arbitrary. We could have defined the same function as above,
but with the name square instead of f; then to use it we use the new function name instead of
the old:
>>> def square (x):
... return x*x
1.1 What is Python?
Python is a powerful modern computer programming language. It bears some similarities to
Fortran, one of the earliest programming languages, but it is much more powerful than Fortran.
Python allows you to use variables without declaring them (i.e., it determines types implicitly),
and it relies on indentation as a control structure. You are not forced to define classes in Python
(unlike Java) but you are free to do so when convenient.
Python was developed by Guido van Rossum, and it is free software. Free as in “free beer,” in that
you can obtain Python without spending any money. But Python is also free in other important
ways, for example you are free to copy it as many times as you like, and free to study the source
code, and make changes to it. There is a worldwide movement behind the idea of free software,
initiated in 1983 by Richard Stallman.1
This document focuses on learning Python for the purpose of doing mathematical calculations.
We assume the reader has some knowledge of basic mathematics, but we try not to assume any
previous exposure to computer programming, although some such exposure would certainly be
helpful. Python is a good choice for mathematical calculations, since we can write code quickly, test
it easily, and its syntax is similar to the way mathematical ideas are expressed in the mathematical
literature. By learning Python you will also be learning a major tool used by many web developers.
1.2 Installation and documentation
If you use Mac OS X or Linux, then Python should already be installed on your computer by
default. If not, you can download the latest version by visiting the Python home page, at
http://www.python.org
where you will also find loads of documentation and other useful information. Windows users can
also download Python at this website. Don’t forget this website; it is your first point of reference
for all things Python. You will find there, for example, reference [1], the excellent Python Tutorial
by Guido van Rossum. You may find it useful to read along in the Tutorial as a supplement to
this document.
2 Getting started
2.1 Running Python as a calculator
The easiest way to get started is to run Python as an interpreter, which behaves similar to the
way one would use a calculator. In the interpreter, you type a command, and Python produces
the answer. Then you type another command, which again produes an answer, and so on.
In OS X or Linux, to start the Python interpreter is as simple as typing the command python
on the command line in a terminal shell. In Windows, assuming that Python has already been
1See http://www.fsf.org or http://www.opensource.org for more information.
4
installed, you need to find Python in the appropriate menu. Windows users may choose to run
Python in a command shell (i.e., a DOS window) where it will behave very similarly to Linux or
OS X.
For all three operating systems (Linux, OS X, Windows) there is also an integrated development
environment for Python named IDLE. If interested, you may download and install this on your computer.2 For help on getting started with IDLE see http://hkn.eecs.berkeley.edu/~dyoo/python/idle_int
Once Python starts running in interpreter mode, using IDLE or a command shell, it produces a
prompt, which waits for your input. For example, this is what I get when I start Python in a
command shell on my Linux box:
doty@brauer:~% python
Python 2.5.2 ( r252 :60911 , Apr 21 2008 , 11:12:42)
[GCC 4.2.3 ( Ubuntu 4.2.3 -2ubuntu7)] on linux2
Type " help", " copyright", " credits" or " license" for more
information.
>>>
where the three symbols >>> indicates the prompt awaiting my input.
So experiment, using the Python interpreter as a calculator. Be assured that you cannot harm
anything, so play with Python as much as you like. For example:
>>> 2*1024
2048
>>> 3+4+9
16
>>> 2**100
1267650600228229401496703205376 L
In the above, we first asked for the product of 2 and 1024, then we asked for the sum of 3, 4, and 9
and finally we asked for the value of 2100. Note that multiplication in Python is represented by ∗,
addition by +, and exponents by **; you will need to remember this syntax. The L appended to
the last answer is there to indicate that this is a long integer; more on this later. It is also worth
noting that Python does arbitrary precision integer arithmetic, by default:
>>> 2**1000
107150860718626732094842504906000181056140481170553 3607443750
388370351051124936122493198378815695858127594672917 5531468251
871452856923140435984577574698574803934567774824230 9854210746
050623711418779541821530464749835819412673987675591 6554394607
706291457119647768654216766042983165262438683720566 8069376L
Here is another example, where we print a table of perfect squares:
>>> for n in [1 ,2 ,3 ,4 ,5 ,6]:
... print n **2
...
149
16
25
36
2Both Python and IDLE should be already preinstalled on all Loyola Windows computers.
5
This illustrates several points. First, the expression [1,2,3,4,5,6] is a list, and we print the values
of n2 for n varying over the list. If we prefer, we can print horizontally instead of vertically:
>>> for n in [1 ,2 ,3 ,4 ,5 ,6]:
... print n**2 ,
...
1 4 9 16 25 36
simply by adding a comma at the end of the print command, which tells Python not to move to
a new line before the next print.
These last two examples are examples of a compound command, where the command is divided
over two lines (or more). That is why you see ... on the second line instead of the usual >>>,
which is the interpreter’s way of telling us it awaits the rest of the command. On the third line
we entered nothing, in order to tell the interpreter that the command was complete at the second
line. Also notice the colon at the end of the first line, and the indentation in the second line. Both
are required in compound Python commands.
2.2 Quitting the interpreter
In a terminal you can quit a Python session by CTRL-D. (Hold down the CTRL key while pressing
the D key.) In IDLE you can also quit from the menu.
If the interpreter gets stuck in an infinite loop, you can quit the current execution by CTRL-C.
2.3 Loading commands from the library
Python has a very extensive library of commands, documented in the Python Library Reference
Manual [2]. These commands are organized into modules. One of the available modules is especially
useful for us: the math module. Let’s see how it may be used.
>>> from math import sqrt , exp
>>> exp( -1)
0.36787944117144233
>>> sqrt (2)
1.4142135623730951
We first import the sqrt and exp functions from the math module, then use them to compute
e−1 = 1/e and √2.
Once we have loaded a function from a module, it is available for the rest of that session. When
we start a new session, we have to reload the function if we need it.
Note that we could have loaded both functions sqrt and exp by using a wildcard *:
>>> from math import *
which tells Python to import all the functions in the math module.
What would have happened if we forgot to import a needed function? After starting a new session,
if we type
>>> sqrt (2)
Traceback ( most recent call last ):
File "<stdin >", line 1, in <module >
NameError: name ’sqrt ’ is not defined
6
we see an example of an error message, telling us that Python does not recognize sqrt.
2.4 Defining functions
It is possible, and very useful, to define our own functions in Python. Generally speaking, if you
need to do a calculation only once, then use the interpreter. But when you or others have need to
perform a certain type of calculation many times, then define a function. For a simple example,
the compound command
>>> def f(x):
... return x*x
...
defines the squaring function f(x) = x2, a popular example used in elementary math courses. In
the definition, the first line is the function header where the name, f, of the function is specified.
Subsequent lines give the body of the function, where the output value is calculated. Note that
the final step is to return the answer; without it we would never see any results. Continuing the
example, we can use the function to calculate the square of any given input:
>>> f(2)
4
>>> f (2.5)
6.25
The name of a function is purely arbitrary. We could have defined the same function as above,
but with the name square instead of f; then to use it we use the new function name instead of
the old:
>>> def square (x):
... return x*x