Académique Documents
Professionnel Documents
Culture Documents
www.ntnu.no
Part I Basics
www.ntnu.no
Introduction Python vs Other Languages Basics Basic Types Syntax Booleans type if statement Variables Syntax Assignments References Copying
www.ntnu.no
Why Python?
Python is. . . Free and open source It is a scripting language, meaning that it is interpreted It is modern: object oriented, exception handling, dynamic typing etc. Plenty of libraries, in particular scientic ones: linear algebra;
visualisation tools: plotting, image analysis; dierential equations solving; symbolic computations; statistics ; etc. Many possible usages: Scientic computing (of course :-)), scripting, web sites, text parsing, etc. Used by YouTube, Google, NASA, Los Alamos, NSA among others
www.ntnu.no
Python vs language XX
C++ Object oriented/functional and compiled. Quite fast. Static binding. Java Object oriented only. Very few scientic libraries. C, FORTRAN Very low level compiled language. Very fast. Useful in some CPU critical situations. php, ruby Other interpreted languages. PHP is web oriented. Ruby is as exible as python but less scientic oriented. MATLAB Tool for matrix computation that evolved for scientic computing. The scientic library is huge but it is not designed as a programming language. Quite expensive. License.
www.ntnu.no
Demo
Demo
www.ntnu.no
Introduction Python vs Other Languages Basics Basic Types Syntax Booleans type if statement Variables Syntax Assignments References Copying
www.ntnu.no
Numbers
A number may be an integer, a real number or a complex number. The usual operations are + and - addition and substraction * and / multiplication and division ** power // integer division
2 * * ( 2 + 2 ) # 16 1j * * 2 # -1
www.ntnu.no
Strings
Strings are lists of characters, enclosed by simple or double quotes:
valid string " string with double quotes "
www.ntnu.no
Strings
Strings are lists of characters, enclosed by simple or double quotes:
valid string " string with double quotes "
You may also use triple quotes for strings including a carriage return:
""" This is a long , long string """
www.ntnu.no
10
Blocks
Pythons blocks are dened by indentation. if <condition>:
else:
www.ntnu.no
11
Indentation
The indentation must be consistent across a block. I personally recommend using tabs. Use whatever you like but dont mix spaces and tabs!!
www.ntnu.no
Introduction Python vs Other Languages Basics Basic Types Syntax Booleans type if statement Variables Syntax Assignments References Copying
www.ntnu.no
13
Conditional Expressions
Denition
A conditional expression is an expression that may have the value True or False.
www.ntnu.no
13
Conditional Expressions
Denition
A conditional expression is an expression that may have the value True or False. Some common operators that yield conditional expressions are: ==, != <, >, <=, >= One combines dierent boolean values with or and and not gives the logical negation of the expression that follows
www.ntnu.no
14
Boolean Operators
Denition
The boolean operators are and, or and not.
www.ntnu.no
14
Boolean Operators
Denition
The boolean operators are and, or and not. They work in a peculiar way: a or b or c returns the rst element that is evaluated to be True (or the last element).
Example
0 or 1 # 1 0 or " " or 10 # 10 1 and 0 # 0
www.ntnu.no
15
if statement
Conditional Statement
A conditional statement delimits a block that will be executed if the condition is true. An optional block, started with the keyword else will be executed if the condition is not fullled.
www.ntnu.no
15
if statement
Conditional Statement
A conditional statement delimits a block that will be executed if the condition is true. An optional block, started with the keyword else will be executed if the condition is not fullled.
x = ... if x > = 0 : < block > else : < block >
www.ntnu.no
Introduction Python vs Other Languages Basics Basic Types Syntax Booleans type if statement Variables Syntax Assignments References Copying
www.ntnu.no
17
Variables
Variables
A variable is a reference to an object. An object may have several references. One uses the assignment operator = to assign a value to a variable.
Example
x = [3 , 4 ] # a list object is created y = x # this object now has two labels : x and y del x # we delete one of the references del y # both references are removed : the object is deleted
www.ntnu.no
18
Assignments
You may assign several variables at the same time:
a = b = 3
www.ntnu.no
18
Assignments
You may assign several variables at the same time:
a = b = 3
www.ntnu.no
18
Assignments
You may assign several variables at the same time:
a = b = 3
Sometimes it is convenient to use the automatic packing/unpacking of tuples (we come back on this later):
a , b = b , a # here we swap the contents of a and b
www.ntnu.no
19
Assignment
Variables are References
>>> x = [0, 1, 2] # y = x cause x and y to point # at the same list >>> y = x # changes to y also change x >>> y[1] = 6 >>> print x [0, 6, 2] # re-assigning y to a new list # decouples the two lists >>> y = [3, 4]
!""#$%&'%()*+',('")-./'*()+'0'+'%*'"1))
x y x y x y
0 6 2 0 6 2 3 4
0 1 2
www.ntnu.no
20
Copy
To create a copy of an object use the function copy of the module copy:
c = [3 , 4 ] d = copy ( c ) d[0] = 0 c # [3 , 4 ] d # [0 , 4 ]
www.ntnu.no
20
Copy
To create a copy of an object use the function copy of the module copy:
c = [3 , 4 ] d = copy ( c ) d[0] = 0 c # [3 , 4 ] d # [0 , 4 ]
www.ntnu.no
Part II Iterating
www.ntnu.no
Lists Syntax Operations Belonging Loops Syntax Comprehension Plotting Slicing Denitions Examples O-bound Insertions Strides
www.ntnu.no
23
Lists
Lists
A python list is an ordered list of objects, enclosed in square brackets. One accesses elements of a list using zero-based indices inside square brackets.
www.ntnu.no
24
List Examples
Example
L1 = [1 , 2 ] L1 [ 0 ] # 1 L1 [ 1 ] # 2 L1 [ 2 ] # raises IndexError L2 = [ a , 1 , [3 , 4 ] ] L2 [ 0 ] # a L2 [ 2 ] [ 0 ] # 3 L2 [ - 1 ] # last element : [3 , 4 ] L2 [ - 2 ] # second to last : 1
www.ntnu.no
25
List Utilities
www.ntnu.no
25
List Utilities
www.ntnu.no
26
Altering a List
Use append to append an element to a list:
L = [ a , b , c ] L [ - 1 ] # c L . append ( d ) L # L is now [ a , b , c , d ] L [ - 1 ] # d
www.ntnu.no
26
Altering a List
Use append to append an element to a list:
L = [ a , b , c ] L [ - 1 ] # c L . append ( d ) L # L is now [ a , b , c , d ] L [ - 1 ] # d
www.ntnu.no
27
Operations on Lists
Adding two lists concatenates them:
Example
L1 = [1 , 2 ] L2 = [3 , 4 ] L = L1 + L2 # [1 , 2 , 3 , 4 ]
www.ntnu.no
27
Operations on Lists
Adding two lists concatenates them:
Example
L1 = [1 , 2 ] L2 = [3 , 4 ] L = L1 + L2 # [1 , 2 , 3 , 4 ]
Logically, multiplying a list with an integer concatenates the list with itself, in other word n*L is equivalent to L + L + + L.
n times
Example
L = [1 , 2 ] 3 * L # [1 , 2 , 1 , 2 , 1 , 2 ]
www.ntnu.no
28
Belonging to a list
Denition
The keywords in and not in determine whether an element belongs to a list (similar to and / in mathematics).
www.ntnu.no
28
Belonging to a list
Denition
The keywords in and not in determine whether an element belongs to a list (similar to and / in mathematics).
Example
L = [ a , 1 , b , 2 ] a in L # True 3 in L # False 4 not in L # True
www.ntnu.no
Lists Syntax Operations Belonging Loops Syntax Comprehension Plotting Slicing Denitions Examples O-bound Insertions Strides
www.ntnu.no
30
for loop
for loop
A for loop allows to loop through a list using an index variable. This variable is successively equal to all the elements in the list. The keyword break stops the loop at any time.
www.ntnu.no
30
for loop
for loop
A for loop allows to loop through a list using an index variable. This variable is successively equal to all the elements in the list. The keyword break stops the loop at any time.
Example
L = [1 , 2 , 10 ] for s in L : print s * 2 , # output : 2 4 20
www.ntnu.no
31
Indentation
Blocks in python
Blocks are dened by indentation in python. They are always started by a colon in the preceding line. The part to be repeated in the for loop has to be properly indented:
for elt in my_list : do_something () something_else () etc print " loop finished " # outside the for block
www.ntnu.no
32
Repeating a Task
One typical use of the for loop is to repeat a certain task a xed number of time using range:
n = 30 for i in range ( n ) : do_something # this gets executed n times
www.ntnu.no
33
Comprehensive lists
A convenient way to build up lists is to use the comprehensive lists construct, possibly with a conditional inside.
Denition
The syntax of a comprehensive list is
[ < expr > for < x > in < list > ]
www.ntnu.no
33
Comprehensive lists
A convenient way to build up lists is to use the comprehensive lists construct, possibly with a conditional inside.
Denition
The syntax of a comprehensive list is
[ < expr > for < x > in < list > ]
Example
L = [2 , 3 , 10 , 1 , 5 ] L2 = [ x * 2 for x in L ] # [4 , 6 , 20 , 2 , 10 ] L3 = [ x * 2 for x in L if 4 < x < = 10 ] # [ 20 , 10 ]
www.ntnu.no
Lists Syntax Operations Belonging Loops Syntax Comprehension Plotting Slicing Denitions Examples O-bound Insertions Strides
www.ntnu.no
35
Plot
plot needs a list of x values and a list of y values. If a single list is given, the list of x values range(len(y)) is assumed. You may use the keyword argument label to give your curves a name, and then show them using legend.
x = .2 x1 = [ sin (. 3 * n * x ) for n in range ( 20 ) ] x2 = [ sin ( 2 * n * x ) for n in range ( 20 ) ] plot ( x1 , label = 0 . 3 ) plot ( x2 , label = 2 ) legend ()
www.ntnu.no
36
Example
Plotting is carried out in the same fashion as in MATLAB.
xs = linspace (0 , 2 * pi , 100 ) plot ( xs , [ sin ( 2 * x ) + cos ( 3 * x ) for x in xs ] , label = my sine )
my sine
www.ntnu.no
Lists Syntax Operations Belonging Loops Syntax Comprehension Plotting Slicing Denitions Examples O-bound Insertions Strides
www.ntnu.no
38
Creating sublists
Slicing
Slicing a list between i and j is creating a copy of its element starting from element at index i and ending just before j .
www.ntnu.no
38
Creating sublists
Slicing
Slicing a list between i and j is creating a copy of its element starting from element at index i and ending just before j .
www.ntnu.no
38
Creating sublists
Slicing
Slicing a list between i and j is creating a copy of its element starting from element at index i and ending just before j .
Example
L = [ C , l , a , u , s ] L [ 1 : 4 ] # remove one element and take three from there : # [ l , a , u ]
www.ntnu.no
39
Partial slicing
One may omit the rst or last bound of the slicing:
L = [ C , l , a , u , s ] L [ 1 : ] # [ l , a , u , s ] L [ : 3 ] # [ C , l , a ] L [ - 2 : ] # [ u , s ] L [ : - 2 ] # [ C , l , a ] L [ : ] # the whole list
www.ntnu.no
0 L[2:]
Rule of thumb
-3
-2
-1
Taking all elements from index 2 included amounts to remove the rst two elements
www.ntnu.no
0 L[2:]
Rule of thumb
-3
-2
-1
Taking all elements from index 2 included amounts to remove the rst two elements
0 L[:2]
Rule of thumb
-3
-2
-1
Taking all elements until index 2 excluded amounts to keep only the rst two elements
www.ntnu.no
0 L[:-2]
Rule of thumb
-3
-2
-1
Taking all elements until index -2 excluded amounts to remove the last two elements
www.ntnu.no
0 L[:-2]
Rule of thumb
-3
-2
-1
Taking all elements until index -2 excluded amounts to remove the last two elements
0 L[-2:]
Rule of thumb
-3
-2
-1
Taking all elements from index -2 included amounts to keep only the last two elements
www.ntnu.no
0 L[2:-1]
Rule of thumb
-3
-2
-1
L[i:-j] amounts to remove the rst i elements and remove the last j elements.
www.ntnu.no
0 L[2:-1]
Rule of thumb
-3
-2
-1
L[i:-j] amounts to remove the rst i elements and remove the last j elements.
0 L[2:5]
Rule of thumb
-1
L[i:j] amounts to remove the rst i and keep the j i next ones.
www.ntnu.no
0 L[-4:-1]
Rule of thumb
-5
-4
-3
-2
-1
L[-i:-j] amounts to remove the last j and keep the i j preceding ones.
www.ntnu.no
44
Out-of-bound slices
No errors for out-of-bound slices
Take notice that you never get index errors with out of bound slices, only, possibly, empty lists.
www.ntnu.no
44
Out-of-bound slices
No errors for out-of-bound slices
Take notice that you never get index errors with out of bound slices, only, possibly, empty lists.
Example
L = range ( 4 ) # [0 , 1 , 2 , 3 ] L [ 4 ] # error ! L [ 1 : 100 ] # same as L [ 1 :] L [ - 100 : - 1 ] # same as L [: - 1 ] L [ - 100 : 100 ] # same as L [:] L [ 5 : 0 ] # empty L [ - 2 : 2 ] # empty WHY ?
www.ntnu.no
45
Altering lists
Slicing may be used to alter lists.
L = [0 , 1 , 2 , 3 , 4 ]
Replacement or Deletion
L [ 2 : 3 ] = [ 100 , 200 ] # [0 , 1 , 100 , 200 , 3 , 4 ] L [ 2 : 3 ] = [ ] # [0 , 1 , 200 , 3 , 4 ] L [ 3 : ] = [ ] # [0 , 1 , 200 ]
Insertion
L [ 1 : 1 ] = [ 1000 , 2000 ] # [0 , 1000 , 2000 , 1 , 200 ] L [ 100 : 200 ] = [ e ] # [0 , 1000 , 2000 , 1 , 200 , e ]
www.ntnu.no
46
Strides
Denition
When computing slices one may also specify a stride which is the length of the step from one index to the other. The default stride is one.
www.ntnu.no
46
Strides
Denition
When computing slices one may also specify a stride which is the length of the step from one index to the other. The default stride is one.
Example
L = range ( 100 ) L [ : 10 : 2 ] # [0 , 2 , 4 , 6 , 8 ] L [ : : 20 ] # [0 , 20 , 40 , 60 , 80 ] L [ 10 : 20 : 3 ] # [ 10 , 13 , 16 , 19 ]
www.ntnu.no
www.ntnu.no
www.ntnu.no
49
enthought
Indentation is used to indicate the contents of the function. It is not optional, but a part of the syntax.
www.ntnu.no
50
Function Documentation
Try this out and check the IPython help for that function!
www.ntnu.no
51
Default return
Example
A function always returns a value. If you dont specify any, then the object None is returned.
def f () : ... r = f () print r None
www.ntnu.no
www.ntnu.no
53
Named Arguments
Denition
The argument of a function may be accessed in any order, provided they are named.
www.ntnu.no
54
Examples
Example
def newton (f , x0 , tol ) : ... # note the order of the arguments in this call : newton ( tol = 1e -3 , x0 = .1 , f = cos ) # here the first argument is not named newton ( cos , tol = 1e -3 , x0 = . 1 ) # ok newton ( cos , .1 , tol = 1e - 3 ) # ok # but you can t have anonymous args after named ones newton ( f = cos , .1 , tol = 1e - 3 ) # error !
www.ntnu.no
55
Default Arguments
Denition
An argument may be given a default value with the equal sign.
www.ntnu.no
55
Default Arguments
Denition
An argument may be given a default value with the equal sign.
Example
def newton (f , x0 , tol = 1e - 6 ) : ... # the tolerance is set to the default 1e - 6 newton ( cos , . 2 ) newton ( x0 = .2 , f = cos ) # the same as above
www.ntnu.no