Notes 20130821
Notes 20130821
Paul Hewitt
21 August 2013
Python (named after Monty, not the reptile) is a language for expressing
algorithms. It is easy to learn for humans (especially anglophones) but ex-
tremely powerful. Ipython (short for interactive python) is an environment
for writing and running python code. If python is analogous to English then
ipython is analogous to Microsoft Word.
1 Python
1. Variables: These have names consisting of a string of letters (upper-
and lowercase), digits, or the underscore . A variable name may not
begin with a digit. Upper- and lowercase letters are distinguished.
Certain reserved words cannot be used as variable names: if, while,
for, and, or, in, . . . We will learn these as we learn the grammar and
syntax of python.
x = 16
tells python to store the value 16 in the variable named x. The expres-
sion
16 = x
has no meaning in python and will generate an error message.
1
3. Binary Operators: python has simple and (mostly) obvious symbols
for basic mathematical operations: +, −, ∗, / mean what you (proba-
bly) think they do. However when dividing integers / yields only the
quotient. If you want the remainder then you can use %. For exponents
use ∗∗. (There is also an operator ∧ but it means something completely
different.)
4. Types: python has built-in objects, including numbers. So, −34206
and 51.17 mean what you think they do. However the operations de-
scribed above behave somewhat differently depending on the type of
object they are applied to. (This is called operator overloading.) The
expressions 7/2 and 7.0/2 yield different results. The basic numerical
types are int, float, long int, and complex. The expression −2 + 3j
yields the complex number with real part −2 and imaginary part 3.
There are other, nonnumerical, types: lists, tuples,
5. Binary relations: The expression 2 < 3 expresses the (true) state-
ment that two is less than three. The expression 5 >= 9 expresses the
(false) statement that five is greater than or equal to nine. To express
equality use the symbol ==. When you evaluate such expressions you
get the built-in values True or False. These values are of boolean type,
named after the famous logician George Boole.
2 Ipython
Let’s explore our first python code.
while x > 0:
d = x%b
print d
x = x/b
What does this seem to do? Work out an example by hand. Write comments
that explain each line.
Now type the above into ipython. What happens? How do we fix things?
To save code for future reuse we type the code into a python module,
which is just a text file with a name like xxxxx.py, then import or %run the
module. The import command is python; %run is an example of ipython
magic. We will see more magic commands later.