Search for notes by fellow students, in your own course and all over the country.
Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.
Document Preview
Extracts from the notes are below, to see the PDF you'll receive please use the links above
Python Basics
S
...
Doty
August 27, 2008
Contents
1 Preliminaries
4
1
...
4
1
...
4
2 Getting started
4
2
...
4
2
...
6
2
...
6
2
...
7
2
...
8
2
...
8
2
...
8
1
3 Python commands
9
3
...
9
3
...
9
3
...
1
The type function
...
2
...
10
3
...
3
Lists and tuples
...
2
...
11
3
...
5
Boolean values
...
3 Expressions
...
4 Operators
...
5 Variables and assignment
...
6 Decisions
...
7 Loops
...
7
...
14
3
...
2
while loop
...
7
...
15
3
...
4
break, continue, and pass
...
8 Lists
...
8
...
17
3
...
2
Sublists (slicing)
...
8
...
18
3
...
4
List methods
...
9 Strings
...
xkcd
...
1
What is Python?
Python is a powerful modern computer programming language
...
Python allows you to use variables without declaring them (i
...
, it determines types implicitly),
and it relies on indentation as a control structure
...
Python was developed by Guido van Rossum, and it is free software
...
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
...
1
This document focuses on learning Python for the purpose of doing mathematical calculations
...
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
...
1
...
If not, you can download the latest version by visiting the Python home page, at
http://www
...
org
where you will also find loads of documentation and other useful information
...
Don’t forget this website; it is your first point of reference
for all things Python
...
You may find it useful to read along in the Tutorial as a supplement to
this document
...
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
...
Then you type another command, which again produes an answer, and so on
...
In Windows, assuming that Python has already been
1
See http://www
...
org or http://www
...
org for more information
...
Windows users may choose to run
Python in a command shell (i
...
, a DOS window) where it will behave very similarly to Linux or
OS X
...
If interested, you may download and install this on your computer
...
eecs
...
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
...
5
...
2
...
2
...
>>>
where the three symbols >>> indicates the prompt awaiting my input
...
Be assured that you cannot harm
anything, so play with Python as much as you like
...
Note that multiplication in Python is represented by ∗,
addition by +, and exponents by **; you will need to remember this syntax
...
It is also worth
noting that Python does arbitrary precision integer arithmetic, by default:
>>> 2 * * 1 0 0 0
1071508607186267320948425049060001810561404811705533607443750
3883703510511249361224931983788156958581275946729175531468251
8714528569231404359845775746985748039345677748242309854210746
0506237114187795418215304647498358194126739876755916554394607
7 0 6 2 9 1 4 5 7 1 1 9 6 4 7 7 6 8 6 5 4 2 1 6 7 6 6 0 4 2 9 8 3 1 6 5 2 6 2 4 3 8 6 8 3 7 2 0 5 6 6 8 0 6 9 3 7 6L
Here is another example, where we print a table of perfect squares:
>>> for n in [1 ,2 ,3 ,4 ,5 ,6]:
...
1
4
9
16
25
36
2
Both Python and IDLE should be already preinstalled on all Loyola Windows computers
...
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
...
print n **2 ,
...
These last two examples are examples of a compound command, where the command is divided
over two lines (or more)
...
on the second line instead of the usual >>>,
which is the interpreter’s way of telling us it awaits the rest of the command
...
Also notice the colon at the end of the first line, and the indentation in the second line
...
2
...
(Hold down the CTRL key while pressing
the D key
...
If the interpreter gets stuck in an infinite loop, you can quit the current execution by CTRL-C
...
3
Loading commands from the library
Python has a very extensive library of commands, documented in the Python Library Reference
Manual [2]
...
One of the available modules is especially
useful for us: the math module
...
>>> from math import sqrt , exp
>>> exp ( -1)
0
...
4142135623730951
We first import the sqrt and exp functions from the math module, then use them to compute
√
e−1 = 1/e and 2
...
When
we start a new session, we have to reload the function if we need it
...
What would have happened if we forgot to import a needed function? After starting a new session,
if we type
>>> sqrt (2)
T r a c e b a c k ( most recent call last ):
File " < stdin > " , line 1 , in < module >
N a m e E r r o r : name ’ sqrt ’ is not d e f i n e d
6
we see an example of an error message, telling us that Python does not recognize sqrt
...
4
Defining functions
It is possible, and very useful, to define our own functions in Python
...
But when you or others have need to
perform a certain type of calculation many times, then define a function
...
return x * x
...
In
the definition, the first line is the function header where the name, f, of the function is specified
...
Note that
the final step is to return the answer; without it we would never see any results
...
5)
6
...
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 ):
...
>>> square (3)
9
>>> square (2
...
25
Actually, a function name is not completely arbitrary, since we are not allowed to use a reserved
word as a function name
...
By the way, Python also allows us to define functions using a format similar to the Lambda
Calculus in mathematical logic
...
Lambda expressions are useful when you
need to define a function in just one line; they are also useful in situations where you need a
function but don’t want to name it
...
These are indistinguishable from Python’s Library modules from the user’s perspective
...
5
Files
Python allows us to store our code in files (also called modules)
...
In doing this, we are essentially defining our own modules,
just like the modules defined already in the Python library
...
when typing the code into a file, but the
indentation is still important
...
py” and then
open a terminal in order to run it:
d o t y @ b r a u e r :~% python
Python 2
...
2 ( r252 :60911 , Apr 21 2008 , 1 1 : 1 2 : 4 2 )
[ GCC 4
...
3 ( Ubuntu 4
...
3 -2 u b u n t u 7 )] on linux2
Type " help " , " c o p y r i g h t" , " c r e d i t s" or " l i c e n s e"
for more i n f o r m a t i o n
...
5)
2
...
Importing a command
from a file works exactly the same as for library modules
...
) Also notice that the file’s extension (
...
2
...
To test the code, import it
into a Python session and try to run it
...
This process is repeated until you are satisfied that the code works
...
There are two types of errors that you will encounter
...
This happens when you make typing errors such as misspellings, or
call something by the wrong name, and for many other reasons
...
2
...
Here’s an example
...
Other possible choices are Notepad for Windows, gedit for
Linux/Gnome, and TextEdit for OS X
...
8
The first line tells Python that this is a script
...
To run the script, type
...
Note that if
you move the script someplace in your search path, then you can run it simply by typing SayHi
...
As far as I know, it is impossible to run Python scripts in a similar way on a Windows machine
...
1
Python commands
Comments
In a Python command, anything after a # symbol is a comment
...
Multiline comments are also possible, and are enclosed by triple double-quote symbols:
" " " This is an e x a m p l e of a long c o m m e n t
that goes on
and on
and on
...
2
Numbers and other data types
Python recognizes several different types of data
...
0
and −23
...
The type float is (roughly) the same as a real
number in mathematics
...
Usually the type of a piece of data is determined implicitly
...
2
...
0)
< type ’ float ’ >
>>> type ( 1 2 3 4 5 6 7 8 9 0 1 )
< type ’ long ’ >
Another useful data type is complex, used for complex numbers
...
3
...
2
Strings
Other useful data types are strings (short for “character strings”); for example "Hello World!"
...
3
...
3
Lists and tuples
Other important sequence types used in Python include lists and tuples
...
Here is how we form lists and tuples:
>>> [1 ,3 ,4 ,1 ,6]
[1 , 3 , 4 , 1 , 6]
>>> type ( [1 ,3 ,4 ,1 ,6] )
< type ’ list ’ >
>>> (1 ,3 ,2)
(1 , 3 , 2)
>>> type ( (1 ,3 ,2) )
< type ’ tuple ’ >
Notice that lists are enclosed in square brackets while tuples are enclosed in parentheses
...
Note that
components of lists may be other lists, and so on:
>>> [1 , 2 , [1 ,2] , [1 ,[1 ,2]] , 5]
[1 , 2 , [1 , 2] , [1 , [1 , 2]] , 5]
By nesting lists within lists in this way, we can build up complicated stuctures
...
Also, repetition is allowed in a sequence, but not in a set
...
2
...
It has three forms
...
, n − 1 starting with 0 and ending with
n − 1
...
For
instance, we have
>> range (1 ,10)
[1 , 2 , 3 , 4 , 5 , 6 , 7 , 8 , 9]
>>> range ( -6 ,0)
[ -6 , -5 , -4 , -3 , -2 , -1]
>>> range (1 ,10 ,2)
[1 , 3 , 5 , 7 , 9]
>>> range (10 ,0 , -2)
[10 , 8 , 6 , 4 , 2]
Note the use of a negative increment in the last example
...
2
...
This is a value which is either True or False
...
3
...
An expression is
anything which produces a value
...
Note that in order for Python to make sense of the last one, the variable x must have a value
assigned and f should be a previously defined function
...
Parentheses
are used to indicate order of operations and grouping, as usual
...
4
Operators
The common binary operators for arithmetic are + for addition, - for subtraction, * for multiplication, and / for division
...
Integer
division is performed so that the result is always another integer (the integer quotient):
11
>>> 25/3
8
>>> 5/2
2
This is a wrinkle that you will always have to keep in mind when working with Python
...
0/3
8
...
0
2
...
Here is another
example of this pitfall:
>>> 2 * * ( 1 / 2 )
1
where we wanted to compute the square root of 2 as the 1 power of 2, but the division in the
2
exponent produced a result of 0 because of integer division
...
5
1
...
This gives the remainder of an integer
division, as in
>>> 5 % 2
1
>>> 25 % 3
1
which shows that 5 mod 2 = 1, and 25 mod 3 = 1
...
Besides the arithmetic operators we need comparison operators: <, >, <=, >=, ==, !=, <>
...
The result of a comparison is always a boolen value
True or False
...
Also, the operator == means
is equal to
...
5
Variables and assignment
An assignment statement in Python has the form variable = expression
...
First the expression on the right hand side is evaluated, then the result is assigned to the
variable
...
The variable retains
the same value until another value is assigned, in which case the previous value is lost
...
>>> x = 2+2
>>> print x
4
In the example above, the assignment statement sets x to 4, producing no output
...
If we execute another assignment to x, then the previous value
is lost
...
5
>>> print x
380
...
0
Remember: A single = is used for assignment, the double == is used to test for equality
...
In computer science, the
statement x = x + 1 is useful
...
In short,
x is incremented by 1
...
The first character must not be a number, and you may not use a reserved word as a variable
name
...
Other examples of legal
variable names are: a, v1, v_1, abc, Bucket, monthly_total, __pi__, TotalAssets
...
6
Decisions
The if–else is used to make choices in Python code
...
The simplest
form is
if c o n d i t i o n :
a c t i o n −1
13
else :
a c t i o n −2
The indentation is required
...
The actions action-1
and action-2 may consist of many statements; they must all be indented the same amount
...
Of course, if the condition evaluates to True then action-1 is executed, otherwise action-2 is executed
...
For example, the
code
x = 1
if x > 0:
print " Friday is w o n d e r f u l"
else :
print " Monday sucks "
print " Have a good w e e k e n d"
results in the output
Friday is w o n d e r f u l
Have a good w e e k e n d
Note that the last print statement is not part of the if-else statement (because it isn’t indented),
so if we change the first line to say x = 0 then the output would be
Monday sucks
Have a good w e e k e n d
More complex decisions may have several alternatives depending on several conditions
...
It means “else if” and one can have any number of elif clauses between the if
and the else
...
If x is
negative or greater than 10000, then digits will be set to zero
...
7
Loops
Python provides two looping commands: for and while
...
3
...
1
for loop
The syntax of a for loop is
14
for i t e m in l i s t :
action
As usual, the action consists of one or more statements, all at the same indentation level
...
The item is a variable name, and list is a list
...
Here is a simple example (the comma at the end of the print
makes all printing occur on the same line):
for i in [2 , 4 , 6 , 0]:
print i ,
This produces the output
2 4 6 0
3
...
2
while loop
The syntax of the while loop is
while c o n d i t i o n :
action
Of course, the action may consist of one or more statements all at the same indentation level
...
Execution of the loop works as follows
...
If True, the body is executed and the condition evaluated again,
and this repeats until the condition evaluates to False
...
Also, if the body does not change the subsequent evaluations of the condition, an infinite
loop may occur
...
To interrupt the execution of an infinite loop, use CTRL-C
...
7
...
For example, the
loop
for n in [10 ,9 ,8 ,7 ,6 ,5 ,4 ,3 ,2 ,1]:
print n ,
else :
print " b l a s t o f f"
15
results in the output
10 9 8 7 6 5 4 3 2 1 b l a s t o f f
and the loop
n =10
while n
n = n
else :
> 0:
n,
- 1
" b l a s t o f f"
has the same effect (it produces identical output)
...
7
...
The
continue statement, also borrowed from C, continues with the next iteration of the loop
...
It can be used when a statement is required syntactically but the
program requires no action
...
for n in range (2 , 10):
for x in range (2 , n ):
if n % x == 0:
print n , ’ equals ’ , x , ’* ’ , n / x
break
else :
# loop fell t h r o u g h w i t h o u t f i n d i n g a factor
print n , ’ is a prime number ’
The above code searches for prime numbers between 2 and 10, and produces the following output
...
8
number
number
2
number
3
number
4
3
Lists
As already mentioned, a list is a finite sequence of items, and one could use the range function to
create lists of integers
...
e
...
For example,
a = [2 , " Jack " , 45 , " 23 W e n t w o r t h Ave " ]
is a perfectly valid list consisting of two integers and two strings
...
16
>>> a = [2 , " Jack " , 45 , " 23 W e n t w o r t h Ave " ]
>>> a
[2 , ’ Jack ’ , 45 , ’ 23 W e n t w o r t h Ave ’]
>>> a [0]
2
>>> a [1]
’ Jack ’
>>> a [2]
45
>>> a [3]
’ 23 W e n t w o r t h Ave ’
Note that the numbering of list items always begins at 0 in Python
...
List items may be assigned a new value; this of course changes the list
...
When
this happens, the previous value is lost:
>>> a
[2002 , ’ Jack ’ , 45 , ’ 23 W e n t w o r t h Ave ’]
>>> a = ’ g o b b l e t y g o o k ’
>>> a
’ gobbletygook’
3
...
1
Length of a list; empty list
Every list has a length, the number of items in the list, obtained using the len function:
>>> x = [9 , 4 , 900 , -45]
>>> len ( x )
4
Of special importance is the empty list of length 0
...
8
...
If x is an existing list, then x[start:end] is the sublist consisting of all items in the original list
at index positions i such that
start ≤ i < end
...
For example,
17
>>>
>>>
[0 ,
>>>
[4 ,
>>>
[0 ,
x = range (0 ,20 ,2)
x
2 , 4 , 6 , 8 , 10 , 12 , 14 , 16 , 18]
x [2:5]
6 , 8]
x [0:5]
2 , 4 , 6 , 8]
When taking a slice, either parameter start or end may be omitted: if start is omitted then the
slice consists of all items up to, but not including, the one at index position end, similarly, if end
is omitted the slice consists of all items starting with the one at position start
...
There is an optional third parameter in a slice, which if present represents an increment, just as
in the range function
...
3
...
3
Joining two lists
Two existing lists may be concatenated together to make a longer list, using the + operator:
>>> [2 ,3 ,6 ,10] + [4 ,0 ,0 ,5 ,0]
[2 , 3 , 6 , 10 , 4 , 0 , 0 , 5 , 0]
3
...
4
List methods
If x is the name of an existing list, we can append an item item to the end of the list using
x
...
append (999)
x
6 , 8 , 9 , 999]
18
A similar method is called insert, which allows an element to be inserted in the list at a specified
position:
>>> x = [ ’a ’ , ’c ’ , ’3 ’ , ’d ’ , ’7 ’]
>>> x
...
insert (3 , ’ junk ’)
>>> x
[100 , ’a ’ , ’c ’ , ’ junk ’ , ’3 ’ , ’d ’ , ’7 ’]
One can also delete the first occurrence of some item in the list (if possible) using remove as
follows:
>>> x
...
pop(i), as in:
>>> x
...
Also, by
default x
...
pop ()
’7 ’
>>> x
[ ’c ’ , ’ junk ’ , ’3 ’ , ’d ’]
Many more methods exist for manipulating lists; consult the Python Tutorial [1] or Python Library
Reference [2] for more details
...
9
Strings
A string in Python is a sequence of characters
...
One major difference is that Python strings are immutable, meaning that we are not allowed to change individual parts of them as we could for a list
...
>>> x = ’ g o b b l e t y g o o k ’
>>> x [2]
’b ’
>>> x [5]
’e ’
>>> x [5] = ’s ’
T r a c e b a c k ( most recent call last ):
File " < stdin > " , line 1 , in < module >
T y p e E r r o r : ’ str ’ object does not s u p p o r t item a s s i g n m e n t
Just as for lists, string items are indexed starting at 0
...
The length function len is the same as for lists, and concatenation is the same too
...
If you need to change an existing string, you must make a new, changed, one
...
For example, you can capitalize an existing string x using x
...
>>> a = ’ g o b b l e t y g o o k is r e f r e s h i n g ’
>>> a
...
See the manuals for details
...
python
...
[2] Guido van Rossum, Python Library Reference Manual, http://docs
...
org