OOP and Scripting in Python Advanced Features

Size: px
Start display at page:

Download "OOP and Scripting in Python Advanced Features"

Transcription

1 OOP and Scripting in Python Advanced Features Giuliano Armano Emanuele Tamponi

2 Advanced Features Structure of a Python Script More on Defining Functions Default Argument Values Keyword Arguments Arbitrary Argument Lists Lambda Forms Exercises More on Lists Functional Programming Tools List Comprehensions Exercises Looping Techniques Iterators Generators Generator Expressions

3 Structure of a Python Script Every Python file (extension.py) is called a module 1 #!/ usr / bin / python 2 3 # Import other modules 4 5 # Define your function, classes, variables and so on 6 7 if name == main : 8 print Hello, World!

4 Structure of a Python Script Every Python file (extension.py) is called a module 1 #!/ usr / bin / python 2 3 # Import other modules 4 5 # Define your function, classes, variables and so on 6 7 if name == main : 8 print Hello, World! To run a Python module from console, python must be in your path

5 Structure of a Python Script Every Python file (extension.py) is called a module 1 #!/ usr / bin / python 2 3 # Import other modules 4 5 # Define your function, classes, variables and so on 6 7 if name == main : 8 print Hello, World! To run a Python module from console, python must be in your path If so, you can open a prompt a write: 1 $ python program_name. py 2 Hello, World!

6 Structure of a Python Script Every Python file (extension.py) is called a module 1 #!/ usr / bin / python 2 3 # Import other modules 4 5 # Define your function, classes, variables and so on 6 7 if name == main : 8 print Hello, World! To run a Python module from console, python must be in your path If so, you can open a prompt a write: 1 $ python program_name. py 2 Hello, World!... otherwise, try with: 1 $ C:\ Python27 \ python. exe program_name. py

7 Default arguments values (1) 1 def ask_ok ( prompt, retries =4, complaint = Yes or no, please! ): 2 while True : 3 ok = raw_input ( prompt ) 4 if ok in ( y, ye, yes ): 5 return True 6 if ok in ( n, no, nop, nope ): 7 return False 8 retries = retries if retries < 0: 10 raise IOError ( refusenik user ) 11 print complaint How can you call this function?

8 Default arguments values (1) 1 def ask_ok ( prompt, retries =4, complaint = Yes or no, please! ): 2 while True : 3 ok = raw_input ( prompt ) 4 if ok in ( y, ye, yes ): 5 return True 6 if ok in ( n, no, nop, nope ): 7 return False 8 retries = retries if retries < 0: 10 raise IOError ( refusenik user ) 11 print complaint How can you call this function? ask_ok( Do you really want to quit? )

9 Default arguments values (1) 1 def ask_ok ( prompt, retries =4, complaint = Yes or no, please! ): 2 while True : 3 ok = raw_input ( prompt ) 4 if ok in ( y, ye, yes ): 5 return True 6 if ok in ( n, no, nop, nope ): 7 return False 8 retries = retries if retries < 0: 10 raise IOError ( refusenik user ) 11 print complaint How can you call this function? ask_ok( Do you really want to quit? ) ask_ok( OK to continue?, 2)

10 Default arguments values (1) 1 def ask_ok ( prompt, retries =4, complaint = Yes or no, please! ): 2 while True : 3 ok = raw_input ( prompt ) 4 if ok in ( y, ye, yes ): 5 return True 6 if ok in ( n, no, nop, nope ): 7 return False 8 retries = retries if retries < 0: 10 raise IOError ( refusenik user ) 11 print complaint How can you call this function? ask_ok( Do you really want to quit? ) ask_ok( OK to continue?, 2) ask_ok( OK to continue?, 2, Only yes or no. )

11 Default Argument Values (2) Default values are evaluated at the point of function definition in the defining scope. 1 >>> i = 5 2 >>> def f( arg =i): 3... print arg 4 >>> i = 6 5 >>> f()

12 Default Argument Values (2) Default values are evaluated at the point of function definition in the defining scope. 1 >>> i = 5 2 >>> def f( arg =i): 3... print arg 4 >>> i = 6 5 >>> f() 1 5

13 Default Argument Values (2) Default values are evaluated at the point of function definition in the defining scope. 1 >>> i = 5 2 >>> def f( arg =i): 3... print arg 4 >>> i = 6 5 >>> f() 1 5 Important warning: default values are evaluated only once. 1 def f(a, L =[]): 2 L. append (a) 3 return L 4 5 >>> print f (1) 6 >>> print f (2) 7 >>> print f (3)

14 Default Argument Values (2) Default values are evaluated at the point of function definition in the defining scope. 1 >>> i = 5 2 >>> def f( arg =i): 3... print arg 4 >>> i = 6 5 >>> f() 1 5 Important warning: default values are evaluated only once. 1 def f(a, L =[]): 2 L. append (a) 3 return L 4 5 >>> print f (1) 6 >>> print f (2) 7 >>> print f (3) 1 [1] 2 [1, 2] 3 [1, 2, 3]

15 Keyword Arguments Functions can also be called using keyword arguments in the form kwarg=value. 1 def opera ( title, author, type ): 2 print title 3 print " -- a ", type, " written by", author Keyword arguments can only be used after positional arguments.

16 Keyword Arguments Functions can also be called using keyword arguments in the form kwarg=value. 1 def opera ( title, author, type ): 2 print title 3 print " -- a ", type, " written by", author Keyword arguments can only be used after positional arguments. Valid function calls:

17 Keyword Arguments Functions can also be called using keyword arguments in the form kwarg=value. 1 def opera ( title, author, type ): 2 print title 3 print " -- a ", type, " written by", author Keyword arguments can only be used after positional arguments. Valid function calls: opera( Romeo and Juliet, Shakespeare, Tragedy )

18 Keyword Arguments Functions can also be called using keyword arguments in the form kwarg=value. 1 def opera ( title, author, type ): 2 print title 3 print " -- a ", type, " written by", author Keyword arguments can only be used after positional arguments. Valid function calls: opera( Romeo and Juliet, Shakespeare, Tragedy ) opera(title= Romeo and Juliet,type= Tragedy,author= Shakespeare )

19 Keyword Arguments Functions can also be called using keyword arguments in the form kwarg=value. 1 def opera ( title, author, type ): 2 print title 3 print " -- a ", type, " written by", author Keyword arguments can only be used after positional arguments. Valid function calls: opera( Romeo and Juliet, Shakespeare, Tragedy ) opera(title= Romeo and Juliet,type= Tragedy,author= Shakespeare ) opera( Romeo and Juliet,type= Tragedy,author= Shakespeare )

20 Keyword Arguments Functions can also be called using keyword arguments in the form kwarg=value. 1 def opera ( title, author, type ): 2 print title 3 print " -- a ", type, " written by", author Keyword arguments can only be used after positional arguments. Valid function calls: opera( Romeo and Juliet, Shakespeare, Tragedy ) opera(title= Romeo and Juliet,type= Tragedy,author= Shakespeare ) opera( Romeo and Juliet,type= Tragedy,author= Shakespeare ) Invalid function calls:

21 Keyword Arguments Functions can also be called using keyword arguments in the form kwarg=value. 1 def opera ( title, author, type ): 2 print title 3 print " -- a ", type, " written by", author Keyword arguments can only be used after positional arguments. Valid function calls: opera( Romeo and Juliet, Shakespeare, Tragedy ) opera(title= Romeo and Juliet,type= Tragedy,author= Shakespeare ) opera( Romeo and Juliet,type= Tragedy,author= Shakespeare ) Invalid function calls: opera(title= Romeo and Juliet, Shakespeare, Tragedy )

22 Keyword Arguments Functions can also be called using keyword arguments in the form kwarg=value. 1 def opera ( title, author, type ): 2 print title 3 print " -- a ", type, " written by", author Keyword arguments can only be used after positional arguments. Valid function calls: opera( Romeo and Juliet, Shakespeare, Tragedy ) opera(title= Romeo and Juliet,type= Tragedy,author= Shakespeare ) opera( Romeo and Juliet,type= Tragedy,author= Shakespeare ) Invalid function calls: opera(title= Romeo and Juliet, Shakespeare, Tragedy ) opera( Romeo and Juliet, Shakespeare, Tragedy,year=1596)

23 **keywords Arguments When a final formal parameter of the form **name is present, it receives a dictionary containing all keyword arguments except for those corresponding to another formal parameter. 1 def cheeseshop ( kind, ** info ): 2 print " -- Do you have any ", kind, "?" 3 print " -- I am sorry, we are all out of", kind 4 print "-" * 40 5 keys = sorted ( info. keys ()) 6 for kw in keys : 7 print kw, ":", info [kw]

24 **keywords Arguments When a final formal parameter of the form **name is present, it receives a dictionary containing all keyword arguments except for those corresponding to another formal parameter. 1 def cheeseshop ( kind, ** info ): 2 print " -- Do you have any ", kind, "?" 3 print " -- I am sorry, we are all out of", kind 4 print "-" * 40 5 keys = sorted ( info. keys ()) 6 for kw in keys : 7 print kw, ":", info [kw] It could be called like this: 1 >>> cheeseshop (" Limburger ", shopkeeper = Michael Palin, 2 client =" John ", sketch =" Cheese Shop Sketch ")

25 **keywords Arguments When a final formal parameter of the form **name is present, it receives a dictionary containing all keyword arguments except for those corresponding to another formal parameter. 1 def cheeseshop ( kind, ** info ): 2 print " -- Do you have any ", kind, "?" 3 print " -- I am sorry, we are all out of", kind 4 print "-" * 40 5 keys = sorted ( info. keys ()) 6 for kw in keys : 7 print kw, ":", info [kw] It could be called like this: 1 >>> cheeseshop (" Limburger ", shopkeeper = Michael Palin, 2 client =" John ", sketch =" Cheese Shop Sketch ") 1 -- Do you have any Limburger? 2 -- I am sorry, we are all out of Limburger client : John 5 shopkeeper : Michael Palin 6 sketch : Cheese Shop Sketch

26 Arbitrary Argument Lists (and unpacking) The *name syntax is used to specify that a function can be called with an arbitrary number of arguments (zero or more). 1 def write_multiple_items ( file, separator, * args ): 2 file. write ( separator. join ( args )) 3 4 >>> write_multiple_item (f,, Hello, world )

27 Arbitrary Argument Lists (and unpacking) The *name syntax is used to specify that a function can be called with an arbitrary number of arguments (zero or more). 1 def write_multiple_items ( file, separator, * args ): 2 file. write ( separator. join ( args )) 3 4 >>> write_multiple_item (f,, Hello, world ) You can also do the reverse: if you have all your arguments in a list or tuple, you can unpack them using the *-operator. 1 >>> range (3, 6) 2 [3, 4, 5] 3 >>> args = [3, 6] 4 >>> range (* args ) 5 [3, 4, 5]

28 Arbitrary Argument Lists (and unpacking) The *name syntax is used to specify that a function can be called with an arbitrary number of arguments (zero or more). 1 def write_multiple_items ( file, separator, * args ): 2 file. write ( separator. join ( args )) 3 4 >>> write_multiple_item (f,, Hello, world ) You can also do the reverse: if you have all your arguments in a list or tuple, you can unpack them using the *-operator. 1 >>> range (3, 6) 2 [3, 4, 5] 3 >>> args = [3, 6] 4 >>> range (* args ) 5 [3, 4, 5] If you have a dictionary, you can use the **-operator. 1 >>> d = { author : Shakespeare, 2 title : Romeo and Juliet, type : Tragedy } 3 >>> opera (** d)

29 Lambda Forms With the lambda keyword, small anonymous functions can be created. 1 def make_incrementor ( n): 2 return lambda x: x + n 3 4 >>> f = make_incrementor (42) 5 >>> f (0) >>> f (5) 8 47

30 Lambda Forms With the lambda keyword, small anonymous functions can be created. 1 def make_incrementor ( n): 2 return lambda x: x + n 3 4 >>> f = make_incrementor (42) 5 >>> f (0) >>> f (5) 8 47 Any number of arguments: lambda a,b,c: a+b+c

31 Lambda Forms With the lambda keyword, small anonymous functions can be created. 1 def make_incrementor ( n): 2 return lambda x: x + n 3 4 >>> f = make_incrementor (42) 5 >>> f (0) >>> f (5) 8 47 Any number of arguments: lambda a,b,c: a+b+c Only a single expression

32 Lambda Forms With the lambda keyword, small anonymous functions can be created. 1 def make_incrementor ( n): 2 return lambda x: x + n 3 4 >>> f = make_incrementor (42) 5 >>> f (0) >>> f (5) 8 47 Any number of arguments: lambda a,b,c: a+b+c Only a single expression Can reference variables from the containing scope

33 Exercises Define a function max(), that returns the maximum value among those received as parameters. It can receive either values as list or a list of values 1 >>> l = [1, 2, 3, 4, 3, 2, 1] 2 >>> max (l) >>> max (3, 4, 5, 6, 2, 3, 4) 5 6 Define a function histogram() that takes a string as first parameter, then an arbitrary number of parameters in the form bin_label=frequency and prints the relative histogram on the screen 1 >>> histogram (" Population of Pincoland ", =10, 2005=15, 2010=12) 3 Population of Pincoland ********** *************** ************

34 Methods of list Objects list.append(x), adds x as last element list.extend(l), the same as list + L list.insert(i, x), inserts x before the element at position i list.remove(x), removes the first occurrence of x list.pop([i]), removes the last (or i-th) element list.index(x), returns the position of x (first occurrence) list.count(x), counts the occurrences of x list.sort(), sorts the list in place list.reverse(), reverses the elements of the list, in place

35 Methods of list Objects list.append(x), adds x as last element list.extend(l), the same as list + L list.insert(i, x), inserts x before the element at position i list.remove(x), removes the first occurrence of x list.pop([i]), removes the last (or i-th) element list.index(x), returns the position of x (first occurrence) list.count(x), counts the occurrences of x list.sort(), sorts the list in place list.reverse(), reverses the elements of the list, in place Reminder: lists (square brackets) are mutable objects, tuples (standard brackets) are immutable objects.

36 filter, reduce...

37 filter, reduce... filter(function, sequence), returns a sequence consisting of those items from the sequence for which function(item) is true 1 def f(x): 2 return x % 2!= 0 and x % 3!= 0 3 >>> filter (f, range (2, 25)) 4 [5, 7, 11, 13, 17, 19, 23]

38 filter, reduce... filter(function, sequence), returns a sequence consisting of those items from the sequence for which function(item) is true 1 def f(x): 2 return x % 2!= 0 and x % 3!= 0 3 >>> filter (f, range (2, 25)) 4 [5, 7, 11, 13, 17, 19, 23] reduce(function, sequence), returns a single value constructed by calling the binary function on the first two items of the sequence, then on the result and the next item, and so on 1 def add (x, y): 2 return x + y 3 4 >>> reduce ( add, range (1, 11)) 5 55

39 filter, reduce... filter(function, sequence), returns a sequence consisting of those items from the sequence for which function(item) is true 1 def f(x): 2 return x % 2!= 0 and x % 3!= 0 3 >>> filter (f, range (2, 25)) 4 [5, 7, 11, 13, 17, 19, 23] reduce(function, sequence), returns a single value constructed by calling the binary function on the first two items of the sequence, then on the result and the next item, and so on 1 def add (x, y): 2 return x + y 3 4 >>> reduce ( add, range (1, 11)) 5 55 reduce(function, sequence, start_value), same as before, but use start_value as first parameter for the first run

40 ... and map map(function, sequence), calls function(item) for each of the sequence s items and returns a list of the return values 1 def cube (x): 2 return x* x* x 3 >>> map (cube, range (1, 11)) 4 [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]

41 ... and map map(function, sequence), calls function(item) for each of the sequence s items and returns a list of the return values 1 def cube (x): 2 return x* x* x 3 >>> map (cube, range (1, 11)) 4 [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] More than one sequence may be passed; the function must then have as many arguments as there are sequences, and the sequences must have the same length 1 def add (x, y): 2 return x + y 3 4 >>> map (add, range (8), range (8,16)) 5 [8, 10, 12, 14, 16, 18, 20, 22]

42 List Comprehensions 1 >>> squares = [] 2 >>> for x in range (10): 3... squares. append (x **2) >>> squares 6 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

43 List Comprehensions 1 >>> squares = [] 2 >>> for x in range (10): 3... squares. append (x **2) >>> squares 6 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] List comprehensions provide a concise way to create lists. 1 >>> squares = [ x **2 for x in range (10)]

44 List Comprehensions 1 >>> squares = [] 2 >>> for x in range (10): 3... squares. append (x **2) >>> squares 6 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] List comprehensions provide a concise way to create lists. 1 >>> squares = [ x **2 for x in range (10)] Can you do it with map?

45 List Comprehensions 1 >>> squares = [] 2 >>> for x in range (10): 3... squares. append (x **2) >>> squares 6 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] List comprehensions provide a concise way to create lists. 1 >>> squares = [ x **2 for x in range (10)] Can you do it with map? 1 >>> squares = map ( lambda x: x**2, range (10))

46 List Comprehensions 1 >>> squares = [] 2 >>> for x in range (10): 3... squares. append (x **2) >>> squares 6 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] List comprehensions provide a concise way to create lists. 1 >>> squares = [ x **2 for x in range (10)] Can you do it with map? 1 >>> squares = map ( lambda x: x**2, range (10)) A listcomp consists of square brackets containing an expression followed by a for clause, then zero or more for or if clauses. 1 >>> [( x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x!= y]

47 List Comprehensions 1 >>> squares = [] 2 >>> for x in range (10): 3... squares. append (x **2) >>> squares 6 [0, 1, 4, 9, 16, 25, 36, 49, 64, 81] List comprehensions provide a concise way to create lists. 1 >>> squares = [ x **2 for x in range (10)] Can you do it with map? 1 >>> squares = map ( lambda x: x**2, range (10)) A listcomp consists of square brackets containing an expression followed by a for clause, then zero or more for or if clauses. 1 >>> [( x, y) for x in [1, 2, 3] for y in [3, 1, 4] if x!= y] 1 [(1, 3), (1, 4), (2, 3), (2, 1), (2, 4), (3, 1), (3, 4)]

48 Matrix transpose with Nested List Comprehensions Provide a function transpose(matrix) that returns the transpose of the matrix received as parameter, represented as an array of rows. 1 >>> a_matrix = [ 2... [1, 2, 3, 4], 3... [5, 6, 7, 8], 4... [9, 10, 11, 12], 5... ]

49 Matrix transpose with Nested List Comprehensions Provide a function transpose(matrix) that returns the transpose of the matrix received as parameter, represented as an array of rows. 1 >>> a_matrix = [ 2... [1, 2, 3, 4], 3... [5, 6, 7, 8], 4... [9, 10, 11, 12], 5... ] 1 def transpose ( matrix ): 2 transposed = [] 3 for i in range ( len ( matrix [0])): 4 transposed_row = [] 5 for row in matrix : 6 transposed_row. append ( row [i]) 7 transposed. append ( transposed_row ) 8 return transposed

50 Matrix transpose with Nested List Comprehensions Provide a function transpose(matrix) that returns the transpose of the matrix received as parameter, represented as an array of rows. 1 >>> a_matrix = [ 2... [1, 2, 3, 4], 3... [5, 6, 7, 8], 4... [9, 10, 11, 12], 5... ] 1 def transpose ( matrix ): 2 transposed = [] 3 for i in range ( len ( matrix [0])): 4 transposed_row = [] 5 for row in matrix : 6 transposed_row. append ( row [i]) 7 transposed. append ( transposed_row ) 8 return transposed 1 def transpose ( matrix ): 2 cols = len ( matrix [0]) 3 return [[ row [ i] for row in matrix ] for i in range ( cols )]

51 Exercises Using reduce(), write a function max() that takes a list of numbers and returns the largest one Write a program that maps a list of words into a list of integers representing the lengths of the corresponding words Write a function find_longest_word() that takes a list of words and returns the length of the longest one Write a function remove_odd_words() that takes a list of words and returns a list of those that have an even length (use filter())

52 Looping Techniques (1)

53 Looping Techniques (1) enumerate(l), gets the position index and corresponding value 1 >>> for i, v in enumerate ([ tic, tac, toe ]): 2... print i, v tic 5 1 tac 6 2 toe

54 Looping Techniques (1) enumerate(l), gets the position index and corresponding value 1 >>> for i, v in enumerate ([ tic, tac, toe ]): 2... print i, v tic 5 1 tac 6 2 toe zip(), pairs entries of two or more sequences 1 >>> primes = [2, 3, 5, 7, 11, 13, 17] 2 >>> squares = [ x **2 for x in primes ] 3 >>> for p, s in zip ( primes, squares ): 4... print {0} squared is {1}.. format (p, s) squared is squared is

55 Looping Techniques (2) reversed(), reverses the order of the items 1 >>> for i in reversed ( range (1, 6, 2)): 2... print i

56 Looping Techniques (2) reversed(), reverses the order of the items 1 >>> for i in reversed ( range (1, 6, 2)): 2... print i sorted(), returns a new sorted list 1 >>> basket = [ apple, orange, apple, 2... pear, orange, banana ] 3 >>> for f in sorted ( set ( basket )): 4... print f apple 7 banana 8 orange 9 pear

57 Looping Techniques (3) dict.iteritems(), accesses keys and values of a dictionary at the same time 1 >>> knights = { gallahad : pure, robin : brave } 2 >>> for k, v in knights. iteritems (): 3... print k, the, v gallahad the pure 6 robin the brave

58 Looping Techniques (3) dict.iteritems(), accesses keys and values of a dictionary at the same time 1 >>> knights = { gallahad : pure, robin : brave } 2 >>> for k, v in knights. iteritems (): 3... print k, the, v gallahad the pure 6 robin the brave It is recommended that you first make a copy of a list if you want to modify it during iteration. Slices are very convenient for this 1 >>> words = [ cat, window, defenestrate ] 2 >>> for w in words [:]: 3... if len (w) > 6: 4... words. insert (0, w) >>> words 7 [ defenestrate, cat, window, defenestrate ]

59 Iterators 1 for x in l: 2 print x

60 Iterators 1 for x in l: 2 print x 1 it = iter ( l) 2 while True : 3 try : 4 x = it. next () 5 print x 6 except StopIteration : 7 break 8 del it

61 Iterators 1 for x in l: 2 print x 1 it = iter ( l) 2 while True : 3 try : 4 x = it. next () 5 print x 6 except StopIteration : 7 break 8 del it The iter() function creates an iterator: an object that has a next() method, which returns the next element in the list if it exists, otherwise it raises a StopIteration exception.

62 Iterators 1 for x in l: 2 print x 1 it = iter ( l) 2 while True : 3 try : 4 x = it. next () 5 print x 6 except StopIteration : 7 break 8 del it The iter() function creates an iterator: an object that has a next() method, which returns the next element in the list if it exists, otherwise it raises a StopIteration exception. Fully customizable using classes: you can decide how your object will iterate in a for loop!

63 Generators

64 Generators Simple and powerful tool for creating iterators

65 Generators Simple and powerful tool for creating iterators Written like regular functions but use yield instead of return 1 def reverse ( data ): 2 for index in range ( len ( data )-1, -1, -1): 3 yield data [ index ]

66 Generators Simple and powerful tool for creating iterators Written like regular functions but use yield instead of return 1 def reverse ( data ): 2 for index in range ( len ( data )-1, -1, -1): 3 yield data [ index ] Iterators are automatically created from function definition 1 >>> for char in reverse ( golf ): 2... print char f 5 l 6 o 7 g

67 Generators Simple and powerful tool for creating iterators Written like regular functions but use yield instead of return 1 def reverse ( data ): 2 for index in range ( len ( data )-1, -1, -1): 3 yield data [ index ] Iterators are automatically created from function definition 1 >>> for char in reverse ( golf ): 2... print char f 5 l 6 o 7 g Local variables and execution state are saved between subsequent calls of next()

68 Generator Expressions Generators created like list comprehensions, but without square brackets. 1 >>> sum ( i* i for i in range (10)) 2 285

69 Generator Expressions Generators created like list comprehensions, but without square brackets. 1 >>> sum ( i* i for i in range (10)) >>> xvec = [10, 20, 30] 2 >>> yvec = [7, 5, 3] 3 >>> sum (x*y for x,y in zip (xvec, yvec )) 4 260

70 Generator Expressions Generators created like list comprehensions, but without square brackets. 1 >>> sum ( i* i for i in range (10)) >>> xvec = [10, 20, 30] 2 >>> yvec = [7, 5, 3] 3 >>> sum (x*y for x,y in zip (xvec, yvec )) >>> from math import pi, sin 2 >>> sine_table = dict (( x, sin ( x* pi /180)) 3... for x in range (0, 91))

71 Generator Expressions Generators created like list comprehensions, but without square brackets. 1 >>> sum ( i* i for i in range (10)) >>> xvec = [10, 20, 30] 2 >>> yvec = [7, 5, 3] 3 >>> sum (x*y for x,y in zip (xvec, yvec )) >>> from math import pi, sin 2 >>> sine_table = dict (( x, sin ( x* pi /180)) 3... for x in range (0, 91)) 1 >>> unique_words = set ( word for line in page 2... for word in line. split ())

72 Generator Expressions Generators created like list comprehensions, but without square brackets. 1 >>> sum ( i* i for i in range (10)) >>> xvec = [10, 20, 30] 2 >>> yvec = [7, 5, 3] 3 >>> sum (x*y for x,y in zip (xvec, yvec )) >>> from math import pi, sin 2 >>> sine_table = dict (( x, sin ( x* pi /180)) 3... for x in range (0, 91)) 1 >>> unique_words = set ( word for line in page 2... for word in line. split ()) 1 >>> data = golf 2 >>> list ( data [i] for i in range ( len ( data ) -1, -1, -1)) 3 [ f, l, o, g ]

Python Lists. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 5, 2011

Python Lists. Stéphane Vialette. LIGM, Université Paris-Est Marne-la-Vallée. October 5, 2011 Python Lists Stéphane Vialette LIGM, Université Paris-Est Marne-la-Vallée October 5, 2011 Stéphane Vialette (LIGM UPEMLV) Python Lists October 5, 2011 1 / 31 Outline 1 Introduction 2 Methods 3 Lists as

More information

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays.

Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. NETB 329 Lecture 4 Data Structures in Python Dictionaries Data type built into Python. Dictionaries are sometimes found in other languages as associative memories or associative arrays. 1 of 70 Unlike

More information

Why Python? Introduction into Python. Introduction: Remarks. Where to get Python and Learn More?

Why Python? Introduction into Python. Introduction: Remarks. Where to get Python and Learn More? Why Python? Introduction into Python Daniel Polani Properties: minimalistic syntax powerful high-level data structures built in scripting, rapid applications, and as we will se AI widely in use (a plus

More information

LECTURE 3 Python Basics Part 2

LECTURE 3 Python Basics Part 2 LECTURE 3 Python Basics Part 2 FUNCTIONAL PROGRAMMING TOOLS Last time, we covered function concepts in depth. We also mentioned that Python allows for the use of a special kind of function, a lambda function.

More information

All programs can be represented in terms of sequence, selection and iteration.

All programs can be represented in terms of sequence, selection and iteration. Python Lesson 3 Lists, for loops and while loops Suffolk One, Ipswich, 4:30 to 6:00 Tuesday Jan 28 Nicky Hughes All programs can be represented in terms of sequence, selection and iteration. 1 Computational

More information

Python: Functions and Generators. Giuseppe Attardi

Python: Functions and Generators. Giuseppe Attardi Python: Functions and Generators Giuseppe Attardi Functional Programming Slides by Felix Hernandez-Campos List Comprehensions >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] >>> [x.strip()

More information

Lecture 7: Python s Built-in. in Types and Basic Statements

Lecture 7: Python s Built-in. in Types and Basic Statements The University of North Carolina at Chapel Hill Spring 2002 Lecture 7: Python s Built-in in Types and Basic Statements Jan 25 1 Built-in in Data Structures: Lists A list is an ordered collection of objects

More information

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING

GE PROBLEM SOVING AND PYTHON PROGRAMMING. Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING GE8151 - PROBLEM SOVING AND PYTHON PROGRAMMING Question Bank UNIT 1 - ALGORITHMIC PROBLEM SOLVING 1) Define Computer 2) Define algorithm 3) What are the two phases in algorithmic problem solving? 4) Why

More information

mith College Computer Science Week 13 CSC111 Fall 2015 (Lab 12, Homework 12) Dominique Thiébaut

mith College Computer Science Week 13 CSC111 Fall 2015 (Lab 12, Homework 12) Dominique Thiébaut mith College Computer Science Week 13 CSC111 Fall 2015 (Lab 12, Homework 12) Dominique Thiébaut dthiebaut@smith.edu This Week: Two Concepts Lists of Lists Class Inheritance Lists of Lists (Chapter 11 Designing

More information

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists

Module 04: Lists. Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10. CS116 Fall : Lists Module 04: Lists Topics: Lists and their methods Mutating lists Abstract list functions Readings: ThinkP 8, 10 1 Consider the string method split >>> name = "Harry James Potter" >>> name.split() ['Harry',

More information

Beyond Blocks: Python Session #1

Beyond Blocks: Python Session #1 Beyond Blocks: Session #1 CS10 Spring 2013 Thursday, April 30, 2013 Michael Ball Beyond Blocks : : Session #1 by Michael Ball adapted from Glenn Sugden is licensed under a Creative Commons Attribution-NonCommercial-ShareAlike

More information

Python for Non-programmers

Python for Non-programmers Python for Non-programmers A Gentle Introduction 2 Yann Tambouret Scientific Computing and Visualization Information Services & Technology Boston University 111 Cummington St. yannpaul@bu.edu Winter 2013

More information

Lecture 21: Functional Programming in Python. List Comprehensions

Lecture 21: Functional Programming in Python. List Comprehensions The University of North Carolina at Chapel Hill Spring 2002 Lecture 21: Functional Programming in March 1 1 List Comprehensions Haskell Lists can be defined by enumeration using list comprehensions Syntax:

More information

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python

Sequence types. str and bytes are sequence types Sequence types have several operations defined for them. Sequence Types. Python Python Sequence Types Sequence types str and bytes are sequence types Sequence types have several operations defined for them Indexing Python Sequence Types Each element in a sequence can be extracted

More information

CSC326 Python Sequences i. CSC326 Python Sequences

CSC326 Python Sequences i. CSC326 Python Sequences i CSC326 Python Sequences ii REVISION HISTORY NUMBER DATE DESCRIPTION NAME 1.0 2011-09 JZ iii Contents 1 Agenda 1 2 while Statement 1 3 Sequence Overview 2 4 String 2 5 Lists 4 6 Dictionary 5 7 Tuples

More information

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 CS 133 - Introduction to Computational and Data Science Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 Introduction to Python II In the previous class, you have

More information

Python I. Some material adapted from Upenn cmpe391 slides and other sources

Python I. Some material adapted from Upenn cmpe391 slides and other sources Python I Some material adapted from Upenn cmpe391 slides and other sources Overview Names & Assignment Data types Sequences types: Lists, Tuples, and Strings Mutability Understanding Reference Semantics

More information

More on Lists. https://docs.python.org/2/tutorial/datastructures.html

More on Lists. https://docs.python.org/2/tutorial/datastructures.html The Rise of Google Announcement HW 2 due today. HW 3 will be posted later this week, when we figure out CADE lab s Python, SciPy, NumPy versions Please go to TA s office hours If you have trouble locating

More information

PTN-102 Python programming

PTN-102 Python programming PTN-102 Python programming COURSE DESCRIPTION Prerequisite: basic Linux/UNIX and programming skills. Delivery Method Instructor-led training (ILT) Duration Four days Course outline Chapter 1: Introduction

More information

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression

\n is used in a string to indicate the newline character. An expression produces data. The simplest expression Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Introduction To Python

Introduction To Python Introduction To Python Week 2: Variables & More Dr. Jim Lupo Asst Dir Computational Enablement LSU Center for Computation & Technology jalupo@cct.lsu.edu 4 Jun 2015, Page 1 of 32 Resources Building Skills

More information

Topic 7: Lists, Dictionaries and Strings

Topic 7: Lists, Dictionaries and Strings Topic 7: Lists, Dictionaries and Strings The human animal differs from the lesser primates in his passion for lists of Ten Best H. Allen Smith 1 Textbook Strongly Recommended Exercises The Python Workbook:

More information

Basic Python 3 Programming (Theory & Practical)

Basic Python 3 Programming (Theory & Practical) Basic Python 3 Programming (Theory & Practical) Length Delivery Method : 5 Days : Instructor-led (Classroom) Course Overview This Python 3 Programming training leads the student from the basics of writing

More information

Software Development Python (Part B)

Software Development Python (Part B) Software Development Python (Part B) Davide Balzarotti Eurecom 1 List Comprehension It is a short way to construct a list based on the content of other existing lists Efficient Elegant Concise List comprehensions

More information

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming

Part I. Wei Tianwen. A Brief Introduction to Python. Part I. Wei Tianwen. Basics. Object Oriented Programming 2017 Table of contents 1 2 Integers and floats Integer int and float float are elementary numeric types in. integer >>> a=1 >>> a 1 >>> type (a) Integers and floats Integer int and float

More information

Python Programming: Lecture 2 Data Types

Python Programming: Lecture 2 Data Types Python Programming: Lecture 2 Data Types Lili Dworkin University of Pennsylvania Last Week s Quiz 1..pyc files contain byte code 2. The type of math.sqrt(9)/3 is float 3. The type of isinstance(5.5, float)

More information

The UOB Python Lectures: Part 1 - Introduction to Python

The UOB Python Lectures: Part 1 - Introduction to Python The UOB Python Lectures: Part 1 - Introduction to Python Hesham al-ammal University of Bahrain 18/3/2013 Twitter: @heshaaam Blog and slides: heshaaam.wordpress.com 1 1 Feel like flying? Ref: xkcd.com 2

More information

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines.

Chapter 1 Summary. Chapter 2 Summary. end of a string, in which case the string can span multiple lines. Chapter 1 Summary Comments are indicated by a hash sign # (also known as the pound or number sign). Text to the right of the hash sign is ignored. (But, hash loses its special meaning if it is part of

More information

Python Lists: Example 1: >>> items=["apple", "orange",100,25.5] >>> items[0] 'apple' >>> 3*items[:2]

Python Lists: Example 1: >>> items=[apple, orange,100,25.5] >>> items[0] 'apple' >>> 3*items[:2] Python Lists: Lists are Python's compound data types. A list contains items separated by commas and enclosed within square brackets ([]). All the items belonging to a list can be of different data type.

More information

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction

ECE 364 Software Engineering Tools Lab. Lecture 3 Python: Introduction ECE 364 Software Engineering Tools Lab Lecture 3 Python: Introduction 1 Introduction to Python Common Data Types If Statements For and While Loops Basic I/O Lecture Summary 2 What is Python? Python is

More information

Compound Data Types 1

Compound Data Types 1 Compound Data Types 1 Chapters 8, 10 Prof. Mauro Gaspari: mauro.gaspari@unibo.it Compound Data Types Strings are compound data types: they are sequences of characters. Int and float are scalar data types:

More information

Variable and Data Type 2

Variable and Data Type 2 The Islamic University of Gaza Faculty of Engineering Dept. of Computer Engineering Intro. To Computers (LNGG 1003) Lab 3 Variable and Data Type 2 Eng. Ibraheem Lubbad March 2, 2017 Python Lists: Lists

More information

Iterators & Generators

Iterators & Generators Iterators & Generators Sequences A sequence is something that you can: Index into Get the length of What are some examples of sequences? Sequences We ve been working with sequences all semester! Examples:

More information

Lecture 0. Introduction to Python. Randall Romero Aguilar, PhD II Semestre 2018 Last updated: July 12, 2018

Lecture 0. Introduction to Python. Randall Romero Aguilar, PhD II Semestre 2018 Last updated: July 12, 2018 Lecture 0 Introduction to Python Randall Romero Aguilar, PhD II Semestre 2018 Last updated: July 12, 2018 Universidad de Costa Rica SP6534 - Economía Computacional Table of contents 1. Getting Python and

More information

Chapter 6: List. 6.1 Definition. What we will learn: What you need to know before: Data types Assignments

Chapter 6: List. 6.1 Definition. What we will learn: What you need to know before: Data types Assignments Chapter 6: List What we will learn: List definition Syntax for creating lists Selecting elements of a list Selecting subsequence of a list What you need to know before: Data types Assignments List Sub-list

More information

Exercise 1. Try the following code segment:

Exercise 1. Try the following code segment: Exercise 1 Try the following code segment: >>> list = [3,4,2,1] >>> for number in list: print 'item %s in list %s' % (number, list) if number > 2: list.remove(number) Pay attention to the print line The

More information

Sequences and iteration in Python

Sequences and iteration in Python GC3: Grid Computing Competence Center Sequences and iteration in Python GC3: Grid Computing Competence Center, University of Zurich Sep. 11 12, 2013 Sequences Python provides a few built-in sequence classes:

More information

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12

List of squares. Program to generate a list containing squares of n integers starting from 0. list. Example. n = 12 List of squares Program to generate a list containing squares of n integers starting from 0 Example list n = 12 squares = [] for i in range(n): squares.append(i**2) print(squares) $ python3 squares.py

More information

Lists and Loops. defining lists lists as queues and stacks inserting and removing membership and ordering lists

Lists and Loops. defining lists lists as queues and stacks inserting and removing membership and ordering lists Lists and Loops 1 Lists in Python defining lists lists as queues and stacks inserting and removing membership and ordering lists 2 Loops in Python for and while loops the composite trapezoidal rule MCS

More information

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University

LISTS WITH PYTHON. José M. Garrido Department of Computer Science. May College of Computing and Software Engineering Kennesaw State University LISTS WITH PYTHON José M. Garrido Department of Computer Science May 2015 College of Computing and Software Engineering Kennesaw State University c 2015, J. M. Garrido Lists with Python 2 Lists with Python

More information

Advanced Python. Executive Summary, Session 1

Advanced Python. Executive Summary, Session 1 Advanced Python Executive Summary, Session 1 OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or use with operators). Everything in Python is an object.

More information

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals:

There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: Numeric Types There are four numeric types: 1. Integers, represented as a 32 bit (or longer) quantity. Digits sequences (possibly) signed are integer literals: 1-123 +456 2. Long integers, of unlimited

More information

Introduction to Python! Lecture 2

Introduction to Python! Lecture 2 .. Introduction to Python Lecture 2 Summary Summary: Lists Sets Tuples Variables while loop for loop Functions Names and values Passing parameters to functions Lists Characteristics of the Python lists

More information

The Practice of Computing Using PYTHON

The Practice of Computing Using PYTHON The Practice of Computing Using PYTHON William Punch Richard Enbody Chapter 6 Lists and Tuples 1 Copyright 2011 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Data Structures 2 Data Structures

More information

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017

CS Introduction to Computational and Data Science. Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 CS 133 - Introduction to Computational and Data Science Instructor: Renzhi Cao Computer Science Department Pacific Lutheran University Spring 2017 Introduction to Python II In the previous class, you have

More information

Introduction to Python, Cplex and Gurobi

Introduction to Python, Cplex and Gurobi Introduction to Python, Cplex and Gurobi Introduction Python is a widely used, high level programming language designed by Guido van Rossum and released on 1991. Two stable releases: Python 2.7 Python

More information

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani

CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvani CIS192: Python Programming Data Types & Comprehensions Harry Smith University of Pennsylvania September 6, 2017 Harry Smith (University of Pennsylvania) CIS 192 Fall Lecture 2 September 6, 2017 1 / 34

More information

A new data type: Lists. March 5, 2018 Sprenkle - CSCI Ø How can we convert from the numerical representa9on to the character?

A new data type: Lists. March 5, 2018 Sprenkle - CSCI Ø How can we convert from the numerical representa9on to the character? Objec9ves A new data type: Lists March 5, 2018 Sprenkle - CSCI111 1 Review How can we convert between characters and their numerical representa9on? Ø How can we convert from the numerical representa9on

More information

Unit 2. Srinidhi H Asst Professor

Unit 2. Srinidhi H Asst Professor Unit 2 Srinidhi H Asst Professor 1 Iterations 2 Python for Loop Statements for iterating_var in sequence: statements(s) 3 Python for While Statements while «expression»: «block» 4 The Collatz 3n + 1 sequence

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2015 Chapter 11 Part 1 The Department of Computer Science Objectives Chapter 11 Data Collections To understand the use of lists (arrays)

More information

Python. Olmo S. Zavala R. Python Data Structures. Lists Tuples Dictionaries. Center of Atmospheric Sciences, UNAM. August 24, 2016

Python. Olmo S. Zavala R. Python Data Structures. Lists Tuples Dictionaries. Center of Atmospheric Sciences, UNAM. August 24, 2016 Center of Atmospheric Sciences, UNAM August 24, 2016 are the most versatile datatype available in. It can be seen as a container of other types of variables. are identified with square brackets and its

More information

LECTURE 2. Python Basics

LECTURE 2. Python Basics LECTURE 2 Python Basics MODULES ''' Module fib.py ''' from future import print_function def even_fib(n): total = 0 f1, f2 = 1, 2 while f1 < n: if f1 % 2 == 0: total = total + f1 f1, f2 = f2, f1 + f2 return

More information

Teaching London Computing

Teaching London Computing Teaching London Computing A Level Computer Science Topic 3: Advanced Programming in Python William Marsh School of Electronic Engineering and Computer Science Queen Mary University of London Aims Further

More information

Introduction to Python

Introduction to Python Introduction to Python Python: very high level language, has high-level data structures built-in (such as dynamic arrays and dictionaries). easy to use and learn. Can be used for scripting (instead of

More information

CIS192 Python Programming

CIS192 Python Programming CIS192 Python Programming Data Types Joseph Cappadona University of Pennsylvania September 03, 2015 Joseph Cappadona (University of Pennsylvania) CIS 192 September 03, 2015 1 / 32 Outline 1 Data Types

More information

dnaseq.py Introduction to Algorithms Recitation 9b October 12, 2011

dnaseq.py Introduction to Algorithms Recitation 9b October 12, 2011 dnaseq.py 1 # Maps integer keys to a set of arbitrary values. 2 class Multidict: 3 # Initializes a new multi-value dictionary, and adds any key-value # 2-tuples in the iterable sequence pairs to the data

More information

Python Basics. Lecture and Lab 5 Day Course. Python Basics

Python Basics. Lecture and Lab 5 Day Course. Python Basics Python Basics Lecture and Lab 5 Day Course Course Overview Python, is an interpreted, object-oriented, high-level language that can get work done in a hurry. A tool that can improve all professionals ability

More information

Dictionaries, Functions 1 / 16

Dictionaries, Functions 1 / 16 Dictionaries, Functions 1 / 16 Lists and Array Reminders To create a list of items, use the [ ] genes = ['SOD1','CDC11','YFG1'] print(genes) print(genes[1]) print(genes[1:]) # everything after slot 1 (incl

More information

Script language: Python Data structures

Script language: Python Data structures Script language: Python Data structures Cédric Saule Technische Fakultät Universität Bielefeld 3. Februar 2015 Immutable vs. Mutable Previously known types: int and string. Both are Immutable but what

More information

Introduction to Computer Programming for Non-Majors

Introduction to Computer Programming for Non-Majors Introduction to Computer Programming for Non-Majors CSC 2301, Fall 2016 Chapter 11 Part 1 Instructor: Long Ma The Department of Computer Science Chapter 11 Data Collections Objectives: To understand the

More information

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26,

Part IV. More on Python. Tobias Neckel: Scripting with Bash and Python Compact Max-Planck, February 16-26, Part IV More on Python Compact Course @ Max-Planck, February 16-26, 2015 36 More on Strings Special string methods (excerpt) s = " Frodo and Sam and Bilbo " s. islower () s. isupper () s. startswith ("

More information

Compound Data Types 2

Compound Data Types 2 Compound Data Types 2 Chapters 10, 11, 12 Prof. Mauro Gaspari: gaspari@cs.unibo.it Objects and Values We know that a and b both refer to a string, but we don t know whether they refer to the same string.

More information

Types, lists & functions

Types, lists & functions Week 2 Types, lists & functions Data types If you want to write a program that allows the user to input something, you can use the command input: name = input (" What is your name? ") print (" Hello "+

More information

CS2304: Python for Java Programmers. CS2304: Sequences and Collections

CS2304: Python for Java Programmers. CS2304: Sequences and Collections CS2304: Sequences and Collections Sequences In Python A sequence type in python supports: The in membership operator. The len() function. Slicing like we saw with strings, s[1:3]. And is iterable (for

More information

Defining Functions. turning expressions into functions. writing a function definition defining and using modules

Defining Functions. turning expressions into functions. writing a function definition defining and using modules Defining Functions 1 Lambda Functions turning expressions into functions 2 Functions and Modules writing a function definition defining and using modules 3 Computing Series Developments exploring an example

More information

SD314 Outils pour le Big Data

SD314 Outils pour le Big Data Institut Supérieur de l Aéronautique et de l Espace SD314 Outils pour le Big Data Functional programming in Python Christophe Garion DISC ISAE Christophe Garion SD314 Outils pour le Big Data 1/ 35 License

More information

Python BASICS. Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc.

Python BASICS. Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc. Python BASICS Introduction to Python programming, basic concepts: formatting, naming conventions, variables, etc. Identikit First appeared in 1991 Designed by Guido van Rossum General purpose High level

More information

List OperaYons. Python Programming, 2/e 2

List OperaYons. Python Programming, 2/e 2 People s Daily With today s announcement, Kim joins the ranks of The Onion s prior Sexiest Man Alive winners, including: 2011: Bashar al- Assad 2010: Bernie Madoff 2009: Charles and David Koch (co- winners)

More information

CPD for GCSE Computing: Practical Sheet 6 February 14

CPD for GCSE Computing: Practical Sheet 6 February 14 Aims Programming Sheet 6 Arrays in Python Section Aim 1 Arrays A variable with many values Understand the idea of an array as a way to combine many values that are assigned to as single variable. 2 While

More information

python 01 September 16, 2016

python 01 September 16, 2016 python 01 September 16, 2016 1 Introduction to Python adapted from Steve Phelps lectures - (http://sphelps.net) 2 Python is interpreted Python is an interpreted language (Java and C are not). In [1]: 7

More information

Programming to Python

Programming to Python Programming to Python Sept., 5 th Slides by M. Stepp, M. Goldstein, M. DiRamio, and S. Shah Compiling and interpreting Many languages require you to compile (translate) your program into a form that the

More information

Python Intro GIS Week 1. Jake K. Carr

Python Intro GIS Week 1. Jake K. Carr GIS 5222 Week 1 Why Python It s simple and easy to learn It s free - open source! It s cross platform IT S expandable!! Why Python: Example Consider having to convert 1,000 shapefiles into feature classes

More information

Overview of List Syntax

Overview of List Syntax Lists and Sequences Overview of List Syntax x = [0, 0, 0, 0] Create list of length 4 with all zeroes x 4300112 x.append(2) 3 in x x[2] = 5 x[0] = 4 k = 3 Append 2 to end of list x (now length 5) Evaluates

More information

ENGR 102 Engineering Lab I - Computation

ENGR 102 Engineering Lab I - Computation ENGR 102 Engineering Lab I - Computation Learning Objectives by Week 1 ENGR 102 Engineering Lab I Computation 2 Credits 2. Introduction to the design and development of computer applications for engineers;

More information

Introduction to Python

Introduction to Python Introduction to Python Version 1.1.5 (12/29/2008) [CG] Page 1 of 243 Introduction...6 About Python...7 The Python Interpreter...9 Exercises...11 Python Compilation...12 Python Scripts in Linux/Unix & Windows...14

More information

Webgurukul Programming Language Course

Webgurukul Programming Language Course Webgurukul Programming Language Course Take One step towards IT profession with us Python Syllabus Python Training Overview > What are the Python Course Pre-requisites > Objectives of the Course > Who

More information

PYTHON. Varun Jain & Senior Software Engineer. Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT. CenturyLink Technologies India PVT LTD

PYTHON. Varun Jain & Senior Software Engineer. Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT. CenturyLink Technologies India PVT LTD PYTHON Varun Jain & Senior Software Engineer Pratap, Mysore Narasimha Raju & TEST AUTOMATION ARCHITECT CenturyLink Technologies India PVT LTD 1 About Python Python is a general-purpose interpreted, interactive,

More information

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords

Worksheet 6: Basic Methods Methods The Format Method Formatting Floats Formatting Different Types Formatting Keywords Worksheet 1: Introductory Exercises Turtle Programming Calculations The Print Function Comments Syntax Semantics Strings Concatenation Quotation Marks Types Variables Restrictions on Variable Names Long

More information

Chapter 2. Python Programming for Physicists. Soon-Hyung Yook. March 31, Soon-Hyung Yook Chapter 2 March 31, / 52

Chapter 2. Python Programming for Physicists. Soon-Hyung Yook. March 31, Soon-Hyung Yook Chapter 2 March 31, / 52 Chapter 2 Python Programming for Physicists Soon-Hyung Yook March 31, 2017 Soon-Hyung Yook Chapter 2 March 31, 2017 1 / 52 Table of Contents I 1 Getting Started 2 Basic Programming Variables and Assignments

More information

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes

GIS 4653/5653: Spatial Programming and GIS. More Python: Statements, Types, Functions, Modules, Classes GIS 4653/5653: Spatial Programming and GIS More Python: Statements, Types, Functions, Modules, Classes Statement Syntax The if-elif-else statement Indentation and and colons are important Parentheses and

More information

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python

06/11/2014. Subjects. CS Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / ) Beginning with Python CS95003 - Applied Robotics Lab Gerardo Carmona :: makeroboticsprojects.com June / 2014 Subjects 1) Beginning with Python 2) Variables 3) Strings 4) Basic arithmetic operators 5) Flow control 6) Comparison

More information

Python. Executive Summary

Python. Executive Summary Python Executive Summary DEFINITIONS OBJECT: a unit of data of a particular type with characteristic functionality (i.e., methods and/or response to operators). Everything in Python is an object. "atomic"

More information

Senthil Kumaran S

Senthil Kumaran S Senthil Kumaran S http://www.stylesen.org/ Agenda History Basics Control Flow Functions Modules History What is Python? Python is a general purpose, object-oriented, high level, interpreted language Created

More information

Data Science Python. Anaconda. Python 3.x. Includes ALL major Python data science packages. Sci-kit learn. Pandas.

Data Science Python. Anaconda.  Python 3.x. Includes ALL major Python data science packages. Sci-kit learn. Pandas. Data Science Python Anaconda Python 3.x Includes ALL major Python data science packages Sci-kit learn Pandas PlotPy Jupyter Notebooks www.anaconda.com Python - simple commands Python is an interactive

More information

1 Modules 2 IO. 3 Lambda Functions. 4 Some tips and tricks. 5 Regex. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 30, / 22

1 Modules 2 IO. 3 Lambda Functions. 4 Some tips and tricks. 5 Regex. Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 30, / 22 1 Modules 2 IO 3 Lambda Functions 4 Some tips and tricks 5 Regex Sandeep Sadanandan (TU, Munich) Python For Fine Programmers May 30, 2009 1 / 22 What are they? Modules are collections of classes or functions

More information

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python

Outline. Simple types in Python Collections Processing collections Strings Tips. 1 On Python language. 2 How to use Python. 3 Syntax of Python Outline 1 On Python language 2 3 4 Marcin Młotkowski Object oriented programming 1 / 52 On Python language The beginnings of Pythons 90 CWI Amsterdam, Guido van Rossum Marcin Młotkowski Object oriented

More information

A tuple can be created as a comma-separated list of values:

A tuple can be created as a comma-separated list of values: Tuples A tuple is a sequence of values much like a list. The values stored in a tuple can be any type, and they are indexed by integers. The important difference is that tuples are immutable, and hence

More information

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/60 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D

Interactive use. $ python. >>> print 'Hello, world!' Hello, world! >>> 3 $ Ctrl-D 1/58 Interactive use $ python Python 2.7.5 (default, Mar 9 2014, 22:15:05) [GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.0.68)] on darwin Type "help", "copyright", "credits" or "license" for more information.

More information

Recall that strings and tuples are immutable datatypes, while lists are mutable datatypes. What does this mean?

Recall that strings and tuples are immutable datatypes, while lists are mutable datatypes. What does this mean? 6.189 Day 4 Readings How To Think Like A Computer Scientist, chapters 7 and 8 6.01 Fall 2009 Course Notes page 27-29 ( Lists and Iterations over lists ; List Comprehensions is optional); sections 3.2-3.4

More information

Class definition. F21SC Industrial Programming: Python. Post-facto setting of class attributes. Class attributes

Class definition. F21SC Industrial Programming: Python. Post-facto setting of class attributes. Class attributes Class definition F21SC Industrial Programming: Python Hans-Wolfgang Loidl School of Mathematical and Computer Sciences, Heriot-Watt University, Edinburgh Semester 1 2014/15 Class definition uses familiar

More information

Python Basics 본자료는다음의웹사이트를정리한내용이니참조바랍니다. PythonBasics

Python Basics 본자료는다음의웹사이트를정리한내용이니참조바랍니다.   PythonBasics Python Basics 본자료는다음의웹사이트를정리한내용이니참조바랍니다. http://ai.berkeley.edu/tutorial.html# PythonBasics Operators >>> 1 + 1 2 >>> 2 * 3 6 Boolean operators >>> 1==0 False >>> not (1==0) True >>> (2==2) and (2==3)

More information

CS150 - Sample Final

CS150 - Sample Final CS150 - Sample Final Name: Honor code: You may use the following material on this exam: The final exam cheat sheet which I have provided The matlab basics handout (without any additional notes) Up to two

More information

Statements 2. a operator= b a = a operator b

Statements 2. a operator= b a = a operator b Statements 2 Outline Note: i=i+1 is a valid statement. Don t confuse it with an equation i==i+1 which is always false for normal numbers. The statement i=i+1 is a very common idiom: it just increments

More information

DM502 Programming A. Peter Schneider-Kamp.

DM502 Programming A. Peter Schneider-Kamp. DM502 Programming A Peter Schneider-Kamp petersk@imada.sdu.dk! http://imada.sdu.dk/~petersk/dm502/! PROJECT PART 1 2 Organizational Details 2 possible projects, each consisting of 2 parts for 1 st part,

More information

CS Advanced Unix Tools & Scripting

CS Advanced Unix Tools & Scripting & Scripting Spring 2011 Hussam Abu-Libdeh slides by David Slater March 4, 2011 Hussam Abu-Libdeh slides by David Slater & Scripting Python An open source programming language conceived in the late 1980s.

More information

Outline. tallying the votes global and local variables call by value or call by reference. of variable length using keywords for optional arguments

Outline. tallying the votes global and local variables call by value or call by reference. of variable length using keywords for optional arguments Outline 1 Histograms tallying the votes global and local variables call by value or call by reference 2 Arguments of Functions of variable length using keywords for optional arguments 3 Functions using

More information

Variables, expressions and statements

Variables, expressions and statements Variables, expressions and statements 2.1. Values and data types A value is one of the fundamental things like a letter or a number that a program manipulates. The values we have seen so far are 2 (the

More information

CS1 Lecture 22 Mar. 8, HW5 available due this Friday, 5pm

CS1 Lecture 22 Mar. 8, HW5 available due this Friday, 5pm CS1 Lecture 22 Mar. 8, 2017 HW5 available due this Friday, 5pm CS1 Lecture 22 Mar. 8, 2017 HW5 available due this Friday, 5pm HW4 scores later today LAST TIME Tuples Zip (and a bit on iterators) Use of

More information

Physics 514 Basic Python Intro

Physics 514 Basic Python Intro Physics 514 Basic Python Intro Emanuel Gull September 8, 2014 1 Python Introduction Download and install python. On Linux this will be done with apt-get, evince, portage, yast, or any other package manager.

More information