Survey
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project
Tutorials Applied Visualizaton Summer Term 2009 Part II - Introducing Python Introducing Python Python Simple, flexible, easy to learn Extendible Used in a vast variety of commercial and open source products • • • • It has nothing to do with reptiles • The name actually comes from “Monty Python’s Flying Circus” Computer Graphics Group Friedrich-Alexander Universität Erlangen - Nürnberg Introducing Python Python • If you already know a programming language such as C or C++ there will be some things you need to get used to • High-level data types allow to express complex operations in a single statement • Statement grouping is done by indentation instead of beginning and ending brackets • No variable or argument declarations are necessary Introducing Python An informal introduction Invoking the interpreter • Last login: Tue May 5 10:43:28 on ttys000 [13:51:28] machine:~ $ python • Ensure that the Python binary is in your PATH /usr/local/bin - Commonly on *nix machines • C:\Python2X\ - Commonly on Windows machines • Introducing Python An informal introduction • Invoking the interpreter Introducing Python An informal introduction • >>> # this is the first comment ... SPAM=1 # a second comment >>> # and a third ... STRING="#this is not a comment" >>> >>> print SPAM 1 >>> print STRING #this is not a comment Introducing Python An informal introduction • Using Python as a calculator >>> >>> >>> >>> 900 >>> >>> >>> 0 >>> 0 >>> 0 • Using Python as a calculator >>> 4 >>> 5 >>> >>> 2 >>> -3 Python 2.5.1 (r251:54863, Jan 17 2008, 19:35:17) [GCC 4.0.1 (Apple Inc. build 5465)] on darwin Type "help", "copyright", "credits" or "license" for more information. • 2+2 (50-5*6)/4 # and a comment 7/3 7/-3 Note that integer division returns the floor of the result Introducing Python An informal introduction • However, variables must be “defined” Assigned to some value before being used ! w = 20 h = 5*9 w*h >>> n Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'n' is not defined >>> x = y = z = 0 x y z No declaration for variables! • Note how Python will tell you when something is wrong Introducing Python An informal introduction • However, variables must be “defined” ! Assigned to some value before being used Introducing Python An informal introduction • Using Python as a calculator • Built in operators >>> n = 7 >>> n 7 >>> • Introducing Python An informal introduction • Using Python as a calculator • Python has full floating point support >>> 3 * 3.75 / 1.5 7.5 >>> 7.0 / 2 3.5 >>> • Note how the argument types determine the result type + - * / % ** >> << & | ^ ~ All binary except ~ Introducing Python An informal introduction • Using Python as a calculator • There even are complex numbers >>> >>> 1j * 1J (-1+0j) >>> 1j * complex(0,1) (-1+0j) >>> 3+1j*3 (3+3j) >>> (1+2j)/(1+1j) (1.5+0.5j) >>> // Introducing Python An informal introduction • Using Python as a calculator • There even are complex numbers Introducing Python An informal introduction • >>> >>> a=1.5+0.5j >>> a.real 1.5 >>> a.imag 0.5 >>> Introducing Python An informal introduction • Using Python as a calculator • The variable _ >>> >>> tax = 12.5 / 100 >>> price = 100.50 >>> price * tax 12.5625 >>> price + _ 113.0625 >>> round(_, 2) 113.06 >>> Using Python as a calculator • Conversions >>> b = 1.5 >>> c = 2 >>> int(b) 1 >>> float(c) 2.0 >>> float(a) Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: can't convert complex to float; use abs(z) >>> abs(a) 1.5811388300841898 >>> Introducing Python An informal introduction • Strings >>> 'hello world' 'hello world' >>> "hello world" 'hello world' >>> 'hey, it\'s python' "hey, it's python" >>> Introducing Python An informal introduction • Strings (escaping long lines) Introducing Python An informal introduction • Strings (triple quotes) >>> >>> ... ... ... ... >>> test = "Hello, this is a long \ ... string, expanding over several lines.\ ... \n \ ... " >>> print test Hello, this is a long string, expanding over several lines. print """ Hello, this is a multi line test string """ Hello, this is a multi line test string >>> Introducing Python An informal introduction • Strings (concatenation / repetition) >>> test = "Hello " + " VTK " + " class!" >>> print test Hello VTK class! >>> greeting = "Hello" >>> >>> test = greeting*3 + " VTK class!" >>> print test HelloHelloHello VTK class! >>> Introducing Python An informal introduction • Strings (subscription / slicing) >>> word = "Hello" >>> word[4] 'o' >>> word[0:2] 'He' >>> word[2:4] 'll' >>> word[:2] 'He' >>> word[2:] 'llo' >>> Introducing Python An informal introduction • Strings are constant in Python Introducing Python An informal introduction • >>> 'X' + word[1:] 'Xello' >>> >>> >>> "Mo" + word[4] 'Moo' >>> >>> word[0] = 'X' # OOPS! Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: 'str' object does not support item assignment Introducing Python An informal introduction • Negative subscripts >>> word[-1] 'o' >>> word[-2] 'l' >>> word[-2:] 'lo' >>> word[:-2] 'Hel' >>> >>> len(word) 5 You can create new strings, however Introducing Python An informal introduction • Slices and indexing H E L L O 0 1 2 3 4 -5 -4 -3 -2 -1 1 : 3 -4 : -2 Introducing Python An informal introduction • Introducing Python Python data types Strings - Odds and Ends • >>> word = u"Hello" # This is a Unicode string now >>> print word Hello • >>> test = r"This is a raw string.\nNote how the escape character stays." >>> print test This is a raw string.\nNote how the escape character stays. >>> >>> word = ur"Hello\n" # Unicode raw >>> print word Hello\n >>> Introducing Python Python data types - Lists • Expressed as list of comma separated values between square brackets >>> >>> alist = [ 'spam', 123, 'eggs', 22.56, 'x'] >>> alist ['spam', 123, 'eggs', 22.559999999999999, 'x'] >>> • • Items can have different types Can even contain lists (dictionaries, tuples,...) >>> >>> a = [ 1, 'test', [ 2, 4 ], 3] >>> a [1, 'test', [2, 4], 3] >>> • Python has a number of compound data types Used to group together other values • Lists • Dictionaries • Tuples • Sets The most versatile is the List Introducing Python Python data types - Lists • Lists can be indexed just like strings • In fact, strings are just immutable lists >>> print a [1, 'test', [2, 4], 3] >>> >>> a[0] 1 >>> a[3] 3 >>> a[-2] [2, 4] >>> a[-3] 'test' >>> Introducing Python Python data types - Lists • Lists can be indexed just like strings • In fact, strings are just immutable lists Introducing Python Python data types - Lists • >>> a[1:-1] ['test', [2, 4]] >>> a[3:] [3] >>> a[:2] [1, 'test'] >>> >>> a[:2] + ['moo', 2*2] [1, 'test', 'moo', 4] >>> 3*a[:3] + ['moo', 2*2] [1, 'test', [2, 4], 1, 'test', [2, 4], 1, 'test', [2, 4], 'moo', 4] >>> Introducing Python Python data types - Lists • Lists can be indexed just like strings • Assignment to slices is also possible >>> [1, >>> >>> [1, >>> >>> [1, >>> >>> [] >>> a 'testtesttest', [256, 4], 3] a[1:3] = [2,3,4,5] a 2, 3, 4, 5, 3] a[-1:] = [] a 2, 3, 4, 5] a[:] = [] a Lists can be indexed just like strings • Unlike strings, you can change list items >>> [1, >>> >>> [1, >>> >>> >>> [1, >>> a 'test', [2, 4], 3] a[1] = 3*a[1] a 'testtesttest', [2, 4], 3] a[2][0] = 256 a 'testtesttest', [256, 4], 3] Introducing Python Python data types - Lists • Lists can be indexed just like strings • Assignment to slices is also possible >>> >>> a = ['a', 'b', 'd','e'] >>> a ['a', 'b', 'd', 'e'] >>> a[2:2] = ['c'] >>> a ['a', 'b', 'c', 'd', 'e'] >>> Introducing Python Python data types - Lists • Lists can be indexed just like strings • Assignment to slices is also possible Introducing Python Python data types - Lists • >>> >>> >>> [1, >>> >>> [1, >>> >>> [1, >>> >>> >>> b = a[:] >>> b ['a', 'b', 'c', 'd', 'e'] >>> >>> len(b) 5 >>> >>> b[len(b)-1] 'e' >>> Introducing Python Python data types - Lists • Methods of lists >>> list.remove(4) >>> list [1, 2, 2.5, 3, 5, 6] >>> list.pop(1) 2 >>> list [1, 2.5, 3, 5, 6] >>> >>> list.index(3) 2 >>> list.index(10) Traceback (most recent call last): File "<stdin>", line 1, in <module> ValueError: list.index(x): x not in list >>> 10 in list False Methods of lists list = [1,2,3] list.append(4) list 2, 3, 4] list.insert(2, 2.5) list 2, 2.5, 3, 4] list.extend([5,6]) list 2, 2.5, 3, 4, 5, 6] Introducing Python Python data types - Lists • Methods of lists >>> >>> 3 >>> >>> >>> [0, >>> >>> >>> [9, >>> list = [3,2,6,4,8,9,0,1,4,5,4] list.count(4) list.sort() list 1, 2, 3, 4, 4, 4, 5, 6, 8, 9] list.reverse() list 8, 6, 5, 4, 4, 4, 3, 2, 1, 0] Introducing Python Python data types - Lists • Introducing Python Python data types - Tuples Methods of lists • Note the difference between append and extend >>> >>> >>> [1, >>> >>> [1, >>> >>> t = ("a", 3, "c") >>> t ('a', 3, 'c') >>> >>> t2 = 1, 'a', 3 >>> t2 (1, 'a', 3) >>> list = [1,2,3] list.extend([4,5]) list 2, 3, 4, 5] list.append([6,7]) list 2, 3, 4, 5, [6, 7]] • • • • Introducing Python Python data types - Tuples >>> empty = () >>> single = "single", >>> >>> empty () >>> single ('single',) >>> • • • You cannot change elements in tuples Tuples are faster than lists Tuples can be converted into lists and vice-versa (tuple and list functions) Are defined like lists, but () are used instead of [] Can use the same indexing methods as lists There are no methods on tuples (like append) You can index tuples like lists ([] operator) Introducing Python Python data types - Tuples • Packing and Unpacking >>> >>> (1, >>> >>> 1 >>> 2 >>> 3 • >>> t = 1,2,3 t 2, 3) x,y,z = t x y z Introducing Python Python data types - Sets A set is an unordered collection with no duplicates • >>> list = [ 1, 2, 3, 5, 6, 6, 1, 1, 3 ] >>> set(list) set([1, 2, 3, 5, 6]) >>> Introducing Python Python data types - Dictionaries A collection of key - value pairs • • • • • Enclosed in {}, Form: key:value Keys can be strings and numbers or tuples, if they consists only of strings and numbers In other words: keys must be immutable Values can be any type Introducing Python Python data types - Dictionaries • A collection of key - value pairs >>> a_dict { 1:"hello", "a_value", "a_number":33.23 } • =Enclosed in {},"a_key": Form: key:value >>> a_dict • Keys can 'a_value', be strings 'a_number': and numbers or tuples, if they {1: 'hello', 'a_key': 33.229999999999997} >>> a_dict[1] consists only of strings and numbers 'hello' • In other words: keys must be immutable >>> a_dict["a_number"] 33.229999999999997 >>> a_dict["new_key"] = 42 >>> a_dict {1: 'hello', 'new_key': 42, 'a_key': 'a_value', 'a_number': 33.229999999999997} >>> a_dict["UnknownKey"] Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: 'UnknownKey' >>> Introducing Python Python data types - The del statement • del can be used with lists and dictionaries >>> a_dict {1: 'hello', 'new_key': 42, 'a_key': 'a_value'} >>> del a_dict["a_key"] >>> a_dict {1: 'hello', 'new_key': 42} >>> >>> list = [ 'a', 'b', 2,3,4] >>> list ['a', 'b', 2, 3, 4] >>> del list[2] >>> list ['a', 'b', 3, 4] >>> del list[len(list)-1] >>> list ['a', 'b', 3] >>> Introducing Python Python data types - odds and ends • You can always create empty lists and dictionaries >>> test1 = [] >>> test2 = {} >>> test1 [] >>> test2 {} >>> test2["akey"] = 10 >>> test1.append(2) >>> test1 [2] >>> test2 {'akey': 10} >>> Introducing Python Writing scripts • • • • Usually you won’t use the interpreter directly Create a simple text file to keep your code By convention, these have the ending .py Invoke the interpreter supplying your file machine:~user$ cat test.py greeting = "Hello " + " VTK " + " class!" print greeting machine:~user$ python test.py Hello VTK class! machine:~user$ Introducing Python Writing scripts • You can pass command line parameters [23:42:55] lyra:examples $ cat cmdline.py import sys print sys.argv [23:43:00] lyra:examples $ [23:42:54] lyra:examples $ python cmdline.py 4 83 hello ['cmdline.py', '4', '83', 'hello'] Introducing Python First steps towards programming • Of course, you can use Python for more complicated tasks than adding two and two together >>> a, b = 0, 1 >>> while b < 10: ... print b ... a, b = b, a+b ... 1 1 2 3 5 8 >>> Introducing Python First steps towards programming • Note some details • Multiple assignment for a and b • The while loop • First steps towards programming • • Loops the body until the condition (b < 10) is False # If block if COND: stmnt elif OTHERCOND: stmnt elif EVENOTHERCOND: stmnt else: stmnt Intendation is Pythons way of grouping statements Introducing Python First steps towards programming Control Flow - while and if >>> a, b = 0, 1 >>> while b < 10: ... if b == 3: ... print "WOW, b is ", b ... else: ... print b, ... a, b = b, a+b ... 1 1 2 WOW, b is 3 5 8 >>> Control Flow - while and if # While loop while COND: stmnt stmnt The body of the loop is indented • • Introducing Python Note the behavior of the print statement # OPTIONAL # OPTIONAL # OPTIONAL Introducing Python First steps towards programming • Conditional operators < > <= >= == != # # # # # # Lower than Greater than Lower or equal Greater or equal Equal Not equal and # Logical and or # Logical or not # Logical not • • # REQUIRED • • A COND is anything that evaluates to True or False Interpreted as False are: False, None, numeric zero of all types, empty strings and containers. All other values are interpreted as True Introducing Python First steps towards programming • Control Flow - for Introducing Python First steps towards programming • >>> >>> a = [ 'a', 'moo', 'vtk', 'class' ] >>> for x in a: ... print x, len(x) ... a 1 moo 3 vtk 3 class 5 >>> • • First steps towards programming • >>> [0, >>> [4, >>> [4, >>> >>> ... ... 0 1 >>> This differs from what you might be used to There is no iterating over an arithmetic progression of values Introducing Python Control Flow - for • It is not safe to modify the sequence beeing iterated over - but you can also trick a little >>> for v in a[:]: # Makes a copy(!) of the list! ... if len(v) == 3: ... a.insert(a.index(v)+1, 'moo') ... >>> a ['fooo', 'bar', 'moo', 'foobar'] >>> Control Flow - for • range() does the trick range(10) 1, 2, 3, 4, 5, 6, 7, 8, 9] range(4,10) 5, 6, 7, 8, 9] range(4,10,2) 6, 8] for i in range(10): print i, 2 3 4 5 6 7 8 9 Introducing Python First steps towards programming • break, continue, and else on loops • break breaks out of the smallest enclosing for or while loop • continue continues with the next iteration of the loop • Loop statements may have an else clause • • Executed when the loop terminates normally Not executed when the loop is terminated by break Introducing Python First steps towards programming • break, continue, and else on loops Introducing Python First steps towards programming • >>> for n in range(2,10): ... for x in range(2, n): ... if n % x == 0: ... print n, " = ", x, '*', n/x ... break ... else: ... print n, " is prime number" ... 2 is prime number 3 is prime number 4 = 2 * 2 5 is prime number 6 = 2 * 3 7 is prime number 8 = 2 * 4 9 = 3 * 3 >>> Introducing Python First steps towards programming • Defining functions >>> def fib(n): ... """ Print a Fibonacci series up to n. """ ... a, b = 0, 1 ... while b < n: ... print b, ... a, b = b, a + b ... >>> >>> fib(2000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 >>> pass • The pass statement does nothing • It can be used when a statement is required syntactically, but the program requires no action >>> def foo(): ... pass ... >>> Introducing Python First steps towards programming • Defining functions • def introduces a function definition • Must be followed by function name and parenthesized list of formal parameters • The statements that form the function body start on the next line and must be intended • The first statement of the function can optionally be a string literal, the docstring Introducing Python First steps towards programming • Defining functions • A definition actually introduces only a symbolic name Introducing Python First steps towards programming • Defining functions • A function always returns a value >>> print fib(0) None >>> >>> fib <function fib at 0x24c430> >>> f = fib >>> f(2000) 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 >>> Introducing Python First steps towards programming • Defining functions • Fibonacci variant returning a list Introducing Python First steps towards programming • Defining functions • Local and global function variables >>> def fib2(n): ... result = [] # Local variable to the function ... a, b = 0, 1 ... while b < n: ... result.append(b) ... a, b = b, a + b ... return result ... >>> fib2(2000) [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377, 610, 987, 1597] >>> • A function can also return multiple values! >>> >>> >>> ... ... ... >>> 5 >>> 10 >>> • i = 10 def f(): i = 5 print i f() print i Variables are defined local to the function body Introducing Python First steps towards programming • Defining functions • Local and global function variables >>> def f(): ... print z ... >>> f() Traceback (most recent File "<stdin>", line File "<stdin>", line NameError: global name >>> • • Function arguments • Default values >>> def example(a = 1, b = ‘Hello’, c = []) Default values are evaluated only once, that is at the point of definition, e.g. >>> ... ... ... >>> [1] >>> [1, >>> [1, def f(a, L=[]): L.append(a) return L print f(1) print f(2) 2] print f(3) 2, 3] Defining functions • Local and global function variables >>> >>> >>> ... ... ... ... >>> 10 >>> 25 >>> 25 >>> If the variable is not defined within the function, it will be searched in global scope First steps towards programming • First steps towards programming call last): 1, in <module> 2, in f 'z' is not defined Introducing Python • Introducing Python x = 10 def f(): global x x = 25 print x # global fetches var from global scope x f() x Introducing Python First steps towards programming • Function arguments • You probably wanted this >>> ... ... ... ... ... >>> [1] >>> [2] >>> [3] >>> def f(a, L=None): if L is None: L = [] L.append(a) return L print f(1) print f(2) print f(3) Introducing Python First steps towards programming • Function arguments • Keyword arguments Introducing Python First steps towards programming • Function arguments • Keyword arguments def parrot(voltage, state='a stiff', action='voom'): print "-- This parrot wouldn't", action, print "if you put", voltage, "volts through it." print "-- It's", state, "!" • Could be called in any of the following ways parrot(1000) parrot(action = 'VOOOOOM', voltage = 1000000) parrot('a thousand', state = 'pushing up the daisies') parrot('a million', 'bereft of life', 'jump') Introducing Python First steps towards programming • def parrot(voltage, state='a stiff', action='voom'): print "-- This parrot wouldn't", action, print "if you put", voltage, "volts through it." print "-- It's", state, "!" Function arguments • Dictionary arguments >>> def foo(a = 0, **myargs): ... for k, v in myargs.iteritems(): ... print k, "=", v ... >>> foo(name1='arg1', name2 = 20, anothername=[2,4,'a']) anothername = [2, 4, 'a'] name2 = 20 name1 = arg1 >>> • But those would all be invalid parrot() parrot(voltage=5.0, 'dead') parrot(110, voltage=220) parrot(actor='John Cleese') # # # # required argument missing non-keyword argument following keyword duplicate value for argument unknown keyword Introducing Python First steps towards programming • Function arguments • Arbitrary non-keyword arguments >>> def foo2(*thearguments): ... print thearguments ... >>> foo2(22, 30, 'foo', (1,2)) (22, 30, 'foo', (1, 2)) >>> • • Can be combined with **argument type, but * must come first! Of course, regular arguments can also be there, but they must also precede * and ** forms! Introducing Python First steps towards programming • Function arguments • Unpacking - another powerful feature >>> def example(a, b, c): ... print a, " ", b, " ", c ... >>> list = [ 'Hello', 'VTK', 'class'] >>> >>> example(*list) Hello VTK class >>> Introducing Python First steps towards programming • The docstring (won’t forget that... ;) >>> def foo3(): ... """ This is a rather simple function. """ ... pass ... >>> foo3() >>> print foo3.__doc__ This is a rather simple function. >>> Introducing Python First steps towards programming • Function arguments • Unpacking - another powerful feature >>> def example2(greeting, topic, towhom): ... print greeting, topic, towhom ... >>> dict = { "greeting":"Hello", "topic":"VTK", "towhom":"class" } >>> >>> example2(**dict) Hello VTK class >>> Introducing Python First steps towards programming • The docstring (won’t forget that... ;) • Try it on an internal function >>> print range.__doc__ range([start,] stop[, step]) -> list of integers Return a list containing an arithmetic progression of integers. range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0. When step is given, it specifies the increment (or decrement). For example, range(4) returns [0, 1, 2, 3]. The end point is omitted! These are exactly the valid indices for a list of 4 elements. >>> Introducing Python Modules • • • • A module is a collection of Python statements and functions A modules filename is the modules name with a .py appended You can use existing modules by importing from them You can also create your own modules • Just put your functions into a .py file use that by importing Introducing Python Modules • Using a module is done by importing it >>> cos (2.0) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'cos' is not defined >>> import math >>> math.cos(2.0) -0.41614683654714241 >>> cos (2.0) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'cos' is not defined • import only includes the module namespace Introducing Python Modules • Examples of often used modules • sys - python system functions • os - operating system specific functions • time - timing functions • math - math functions • vtk - VTK bindings • tkinter - Tk bindings • And a whole lot of more (‘Batteries included’) Introducing Python Modules • To get rid of the module tag either import only a single function or all (*) functions >>> from math import cos >>> cos(2.0) -0.41614683654714241 >>> sin(2.0) Traceback (most recent call last): File "<stdin>", line 1, in <module> NameError: name 'sin' is not defined >>> from math import * >>> sin(2.0) 0.90929742682568171 >>> Introducing Python Modules • Listing the contents of a module >>> import math >>> >>> dir(math) ['__doc__', '__file__', '__name__', 'acos', 'asin', 'atan', 'atan2', 'ceil', 'cos', 'cosh', 'degrees', 'e', 'exp', 'fabs', 'floor', 'fmod', 'frexp', 'hypot', 'ldexp', 'log', 'log10', 'modf', 'pi', 'pow', 'radians', 'sin', 'sinh', 'sqrt', 'tan', 'tanh'] >>> • Modules can contain sub-modules!