Some Python codes
Everything is an object
look at a sample of code… assignments, arithmetics, if, print
Basic Datatypes
Python Build-in types
Single- and Double-Quoted

注脚

展开查看详情

1.Understand ing the Basics

2.PRINTING

3.Some Python codes • 6+9 • Print 6+9 • Print “6+9” • aa=6+9 print aa • aa=6 bb=9 aa+bb

4. Print • Python command print – Displays data, values, and expressions • The single and double quotation mark string objects, which are collections of texts surrounded by quotes.

5.Be familiar with Python printing >>> print ("Hello, World! ") Hello, World! >>> "hello" 'hello' >>> "world" 'world' >>> "hello"+"world" 'helloworld'

6.Be familiar with Python printing >>> "hello" * 3 'hellohellohello' >>> "hello" * 300

7. Variables • Are not declared, just assigned • The variable is created the first time you assign it a value • Are references to objects • Type information is with the object, not the reference • Everything in Python is an object

8.Variables • variable: A named piece of memory that can store a value. • Usage: • Compute an expression's result, • store that result into a variable, • and use that variable later in the program. • assignment statement: Stores a value into a variable. • Syntax: name = value • Examples: x = 5 gpa = 3.14 x 5 gpa 3.14 • A variable that has been given a value can be used in expressions. x + 4 is 9 • Exercise: Evaluate the quadratic equation for a given a, b, and c. 8

9. Everything is an object • Everything means >>> x = 7 everything, including >>> x functions and classes 7 (more on this later!) >>> x = 'hello' >>> x 'hello' >>> • Data type is a property of the object and not of the variable

10.Look at a sample of code… Look at a sample of code… assignments, arithmetics, if, print x = 34 - 23 # A comment. y = “Hello” # Another one. z = 3.45 if z == 3.45 or y == “Hello”: x = x + 1 y = y + “ World” # String concat. print x print y

11.Declare a variable and assign its value Example: Area of a rectangle >>> width = 20 >>> height = 45 >>> area = width * height >>> area 900

12.Evaluation of expressions in Python >>> print ("Hello, World! ") Hello, World! >>> 10 + 25 35 >>> 124 – 125 -1 >>> 1/3 0.333333333333333

13. Print of long lines • print : Produces text output on the console. • Syntax: print "Message" print Expression • Prints the given text message or expression value on the console, and moves the cursor down to the next line. print Item1, Item2, ..., ItemN • Prints several messages and/or expressions on the same line. • Example: print "Hello, world!" age = 45 print "You have", 65 - age, "years until retirement" Output: Hello, world! You have 20 years until retirement 13

14. Enough to Understand the Code • Assignment uses = and comparison uses ==. • For numbers +, -, *, /, % are as expected. • Special use of + for string concatenation. • Special use of % for string formatting. • Logical operators are words (and, or, not) not symbols (&&, ||, !). • The basic printing command is “print.” • First assignment to a variable will create it. • Variable types don’t need to be declared. • Python figures out the variable types on its own.

15.Basic Datatypes • Integers (default for numbers) z = 5 / 2 # Answer is 2, integer division. • Floats x = 3.456 • Strings Can use “ ” or ‘ ’ to specify. “abc” ‘abc’ (Same thing.) thing Unmatched ones can occur within the string. “matt’s” Use triple double-quotes for multi-line strings or strings than contain both ‘ and “ inside of them: “““a‘b“c”””

16. Comments • Start comments with # – the rest of line is ignored. • Can include a “documentation string” as the first line of any new function or class that you define. • The development environment, debugger, and other tools use it: it’s good style to include one. def my_function(x, y): “““This is the docstring. This function does blah blah blah.””” # The code would go here...

17.Python Build-in types • Numbers 3.1415 • Strings “Hello World” • Lists [1,2,3,4] • Dictionaries {‘test’: ‘yum’} • Files input=open(‘file.txt’, ‘r’)

18.TEST: What are the outputs? Why? >>> a=3 >>> b=4 >>> a+1 >>> b*3 >>> b/3 >>> b/3.0 >>> b**2 >>> 2+4.0 >>> 2.0**b

19.Hello World Program

20.Hello World Program • Implement by three different languages • In C • In JAVA • In Python

21.“Hello World” in C main() { printf("hello, world\n"); }

22.“Hello World” in C #include <iostream> using namespace std; main() { cout<<“Hello World” ; }

23.“Hello World” in JAVA class myfirstjavaprog { public static void main(String args[]) { System.out.println("Hello World!"); } }

24.“Hello World” in Python print "hello World!"

25.“Hello World” in Python print (“Hello World!!”)

26. Your first Python program- hello.py # This program says hello and asks for my name. hello = 'Hello world! ' print(hello) print('What is your name?') myName = input() print('It is good to meet you, ' + myName)

27.hello.py executed sequentially # This program says hello and asks for my name. Any text following a # sign is a comment. Comments are not # # sign is a comment. Comments are not sign is a comment. Comments are not for the computer, but for you, the programmer. # sign is a comment. Comments are not 1.hello = 'Hello world! ' # assign the string to a name 2.print(hello) # call the print( ) function 3.print('What is your name?') # call the print( ) function 4.myName = input() # call the input( ) function 5.print('It is good to meet you, ' + myName)

28. Arithmetic Expressions • expression: A data value or set of operations to compute a value. Examples: 1 + 4 * 3 42 • Arithmetic operators we will use: • + - * / addition, subtraction/negation, multiplication, division • % modulus, a.k.a. remainder • ** exponentiation • precedence: Order in which operations are computed. • * / % ** have a higher precedence than + - 1 + 3 * 4 is 13 • Parentheses can be used to force a certain order of evaluation. (1 + 3) * 4 is 16 28

29.Integer division • When we divide integers with / , the quotient is also an integer. 3 52 4 ) 14 27 ) 1425 12 135 2 75 54 21 • More examples: • 35 / 5 is 7 • 84 / 10 is 8 • 156 / 100 is 1 • The % operator computes the remainder from a division of integers. 3 43 4 ) 14 5 ) 218 12 20 2 18 15 3 29

30.Real numbers • Python can also manipulate real numbers. • Examples: 6.022 -15.9997 42.0 2.143e17 • The operators + - * / % ** ( ) all work for real numbers. • The / produces an exact answer: 15.0 / 2.0 is 7.5 • The same rules of precedence also apply to real numbers: Evaluate ( ) before * / % before + - • When integers and reals are mixed, the result is a real number. • Example: 1 / 2.0 is 0.5 • The conversion occurs on a per-operator basis. • 7 / 3 * 1.2 + 3 / 2 • 2 * 1.2 + 3 / 2 • 2.4 + 3 / 2 • 2.4 + 1 • 3.4 30

31. Math commands • Python has useful commands for performing calculations. Command name Description Constant Description abs(value) absolute value e 2.7182818... ceil(value) rounds up pi 3.1415926... cos(value) cosine, in radians floor(value) rounds down log(value) logarithm, base e log10(value) logarithm, base 10 max(value1, value2) larger of two values min(value1, value2) smaller of two values round(value) nearest whole number sin(value) sine, in radians sqrt(value) square root • To use many of these commands, you must write the following at the top of your Python program: from math import * 31

32.Numbe rs

33.Number in Action • Perhaps the best way to understand numerical objects is to see them in action. >>> a=3 #Name Created >>> b=4

34.Number in Action >>> a+1, a-1 # (3+1), (3-1) (4,2) >>> b*3, b/2 (12,2)

35.Number in Action >>> 1 / 2.0 0.5 >>> 1/2 0 >>> 1 % 2 1

36. Simple Data Types • Triple quotes useful for multi-line strings >>> s = """ a long ... string with "quotes" or anything else""" >>> s ' a long\012string with "quotes" or anything else' >>> len(s) 45

37.Numbers: Integers • Integer – the equivalent of a C long >>> 132224 • Long Integer – an 132224 >>> 132323 ** 2 unbounded integer value. 17509376329L >>>

38.Numbers: Floating Point • int(x) converts x to an >>> 1.23232 1.2323200000000001 integer >>> print 1.23232 • float(x) converts x to a 1.23232 >>> 1.3E7 floating point 13000000.0 >>> int(2.0) • The interpreter shows 2 a lot of digits >>> float(2) 2.0

39. exercises • Geometric calculations for robots • Speed and acceleration • Pythagoras Theorem • Braitenberg Vehicles. • Logic operators. • Defining functions. • If

40.Numbers: Complex • Built into Python • Same operations are >>> x = 3 + 2j >>> y = -1j supported as integer and >>> x +y float (3+1j) >>> x *y (2-3j) End of lecture 1

41.Numbers are immutable x 4.5 >>> x = 4.5 >>> y=x y >>> y += 3 >>> x 4.5 x 4.5 >>> y y 7.5 7.5

42.Strings

43. Strings • The next major build-in type is the Python STRING --- an ordered collection of characters to store and represent text-based information • Python strings are categorized as immutable sequences --- meaning they have a left-to-right order (sequence) and cannot be changed in place (immutable) • This definition of immutable sequences is sufficient for now. You will learn more from examples.

44. Single- and Double- Quoted • Single- and Double-Quoted strings are the same >>> ‘Hello World’ , “Hello World” • The reason for including both is that it allows you to embed a quote character of the other inside a string >>> “knight’s” , ‘knight”s’

45.Strings in Action • Basic operations: 1. len() length 2. + concatenate 3. * repetition

46. len() • The len build-in function returns the length of strings >>> len(‘abc’) length >>> a=‘abc’ >>> len(a)

47. + • Adding two string objects creates a new string object >>> ‘abc’ + ‘def’ >>> a=‘Hello’ >>> b=‘World’ Hello World with >>> a + b space >>> a+ ‘ ’ +b Concatenation of strings

48. * • Repetition may seem a bit obscure at first, but it comes in handy in a surprising number of contexts • For example, to print a line of 80 dashes >>> print ‘-’ * 80

49. Slices and Indexes

50. Indexes in slices • Characters in a string are numbered with indexes starting at 0: • Example: name = "P. Diddy" index 0 1 2 3 4 5 6 7 characte P . D i d d y r • Accessing an individual character of a string: variableName [ index ] • Example: print name, "starts with", name[0] Output: P. Diddy starts with P 50

51.More examples on Index and slice >>> aa=“SLICEOFSPAM” >>> aa[0], aa[-2] (‘S’,’A’) >>> aa[1:3], aa[1:], aa[:-1] (‘LI’, ‘LICEOFSPAM’, ‘SLICEOFSPA’)

52. String Methods: modifying and checking strings assigned to variables • Assign a string to a variable • In this case “hw” • hw.title() • hw.upper() • hw.isdigit() • hw.islower() • The string held in your variable remains the same • The method returns an altered string • Changing the variable requires reassignment • hw = hw.upper() • hw now equals “HELLO WORLD”

53. Substrings and Methods • len(String) – returns the >>> s = '012345' number of characters in the >>> s[3] String '3' >>> s[1:4] • str(Object) – returns a '123' String representation of the >>> s[2:] Object '2345' >>> s[:4] '0123' >>> s[-2] >>> len(x) '4' 6 >>> str(10.3) '10.3'

54.String Literals: immutable and overloading • Strings are immutable • There is no char type like >>> x = 'hello' >>> x = x + ' there' in C++ or Java >>> x 'hello there' • + is overloaded to do concatenation Example

55. String Literals: Many Kinds • Can use single or double quotes, and three double quotes for a multi-line string >>> 'I am a string' 'I am a string' >>> "So am I!" 'So am I!' >>> s = """And me too! though I am much longer than the others :)""" 'And me too!\nthough I am much longer\nthan the others :)‘ >>> print s And me too! though I am much longer than the others :)‘

56. String Formatting • Similar to C’s printf • <formatted string> % <elements to insert> • Can usually just use %s for everything, it will convert the object to its String representation. >>> "One, %d, three" % 2 'One, 2, three' >>> "%d, two, %s" % (1,3) '1, two, 3' >>> "%s two %s" % (1, 'three') '1 two three' >>>

57. Characters in strings and limitations on strings • string: A sequence of text characters in a program. • Strings start and end with quotation mark " or apostrophe ' characters. • Examples: "hello" "This is a string" "This, too, is a string. It can be very long!" • A string may not span across multiple lines or contain a " character. "This is not a legal String." "This is not a "legal" String either." • A string can represent characters by preceding them with a backslash. • \t tab character • \n new line character • \" quotation mark character • \\ backslash character • Example: "Hello\tthere\nHow are you?" 57

58. Examples of Strings • "hello"+"world" "helloworld" # concatenation • "hello"*3 "hellohellohello" # repetition • "hello"[0] "h" # indexing • "hello"[-1] "o" # (from end) • "hello"[1:4] "ell" # slicing • len("hello") 5 # size • "hello" < "jello" 1 # comparison • "e" in "hello" 1 # search • New line: "escapes: \n " • Line continuation: triple quotes ’’’ • Quotes: ‘single quotes’, "raw strings"

59.Text and File Processing 59 

60.Using len, str.lower and str.upper on STRINGS • len(string) - number of characters in a string (including spaces) • str.lower(string) - lowercase version of a string • str.upper(string) - uppercase version of a string • Example: name = "Martin Douglas Stepp" length = len(name) big_name = str.upper(name) print big_name, "has", length, "characters" Output: MARTIN DOUGLAS STEPP has 20 characters 60

61. raw_input: reading text from input • raw_input : Reads a string of text from user input. • Example: name = raw_input("Howdy, pardner. What's yer name? ") print name, "... what a silly name!" Output: Howdy, pardner. What's yer name? Paris Hilton Paris Hilton ... what a silly name! Homeworks. 1.How can the program of Leila be generalized for our robots? 2.How to use Genetic Algorithm to create interesting texts? 3.How the robot can speak? 4.Invent your own applications of a dialog with little robot , 61 one that you are building.

62.Text processing: FOR loop in text • text processing: Examining, editing, formatting text. • often uses loops that examine the characters of a string one by one • A for loop can examine each character in a string in sequence. • Example: for c in "booyah": print c Output: b o o y a h

63. Strings and numbers: CONVERSIONS • ord(text) - converts a string into a number. • Example: ord("a") is 97, ord("b") is 98, ... • Characters map to numbers using standardized mappings such as ASCII and Unicode. • chr(number) - converts a number into a string. • Example: chr(99) is "c" • Exercise: Write a program that performs a rotation cypher. • e.g. "Attack" when rotated by 1 becomes "buubdl" Task Create a cryptographic systems for 63 your two robots to communicate

64. File processing • Many programs handle data, which often comes from files. • Reading the entire contents of a file: variableName = open("filename").read() Example: file_text = open("bankaccount.txt").read() 64

65. Line-by-line processing • Reading a file line-by-line: for line in open("filename").readlines(): End of statements lecture 2 Example: counting the number of lines in the file count = 0 for line in open("bankaccount.txt").readlines(): count = count + 1 print "The file contains", count, "lines." • Exercise: Write a program to process a file of DNA text, such as: ATGCAATTGCTCGATTAG • Count the percent of C+G present in the DNA. PROBLEM Recall the Genetic Algorithm. Write a Python code for GA. Encode robot’s characteristics in chromosomes. We have done such examples in class. We will use this method for our robots. 65

66.Contain ers

67.Python Objects: Lists, Tuples, Dictionaries • Lists (mutable sets of strings) • var = [] # create list • var = [‘one’, 2, ‘three’, ‘banana’] • Tuples (immutable sets) • var = (‘one’, 2, ‘three’, ‘banana’) • Dictionaries (associative arrays or ‘hashes’) • var = {} # create dictionary • var = {‘lat’: 40.20547, ‘lon’: -74.76322} • var[‘lat’] = 40.2054 • Each has its own set of methods

68. Tuples, Lists, and Strings: Similarities

69.Similar Syntax of tuples and lists • Tuples and lists are sequential containers that share much of the same syntax and functionality. • For conciseness, they will be introduced together. • The operations shown in this section can be applied to both tuples and lists, • but most examples will just show the operation performed on one or the other. • While strings aren’t exactly a container data type, they also happen to share a lot of their syntax with lists and tuples; • so, the operations you see in this section can apply to them as well.

70.How Tuples, Lists, and Strings are defined Defining Tuples • Tuples are defined using parentheses (and commas). >>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’) Defining Lists • Lists are defined using square brackets (and commas). >>> li = [“abc”, 34, 4.34, 23] Defining Strings • Strings are defined using quotes (“, ‘, or “““). >>> st = “Hello World” >>> st = ‘Hello World’ >>> st = “““This is a multi-line string that uses triple quotes.”””

71. Individual access in Tuples, Lists, and Strings • Tuples are defined using parentheses (and commas). >>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’) • Lists are defined using square brackets (and commas). >>> li = [“abc”, 34, 4.34, 23] From last slide • Strings are defined using quotes (“, ‘, or “““). >>> st = “Hello World” >>> st = ‘Hello World’ • We can access individual members of a tuple, list, or string using square bracket “array” notation. >>> tu[1] # Second item in the tuple. ‘abc’ >>> li[1] # Second item in the list. 34 >>> st[1] # Second character in string. ‘e’ This is similar to strings that we discussed last time

72.Looking up an Item in a tuple from last slide 1 -2 -1 0 2 or -3 >>> t = (23, ‘abc’, 4.56, (2,3), ‘def’) Positive index: index count from the left, starting with 0. >>> t[1] ‘abc’ Negative lookup: lookup count from right, starting with –1. >>> t[-3] 4.56

73. Slicing: Return Copy of a Subset, part 1 Value of variable t is a tuple: >>> t = (23, ‘abc’, 4.56, (2,3), ‘def’) Return a copy of the container with a subset of the original members. Start copying at the first index, and stop copying before the second index. >>> t[1:4] (‘abc’, 4.56, (2,3)) You can also use negative indices when slicing. >>> t[1:-1] (‘abc’, 4.56, (2,3))

74.Slicing: Return Copy of a Subset, part 2 >>> t = (23, ‘abc’, 4.56, (2,3), ‘def’) Omit the first index to make a copy starting from the beginning of the container. >>> t[:2] (23, ‘abc’) Omit the second index to make a copy starting at the first index and going to the end of the container. >>> t[2:] (4.56, (2,3), ‘def’) a lre a dy for strings this We illustrated

75. Copying the Whole Container >>> t = (23, ‘abc’, 4.56, (2,3), ‘def’) You can make a copy of the whole tuple using [:]. >>> t[:] (23, ‘abc’, 4.56, (2,3), ‘def’) So, there’s a difference between these two lines: >>> list2 = list1 # 2 names refer to 1 ref # Changing one affects both >>> list2 = list1[:] # Two copies, two refs # They’re independent

76. The ‘in’ Operator in containers • Boolean test whether a value is inside a container: >>> t = [1, 2, 4, 5] >>> 3 in t False >>> 4 in t True >>> 4 not in t False • Be careful: the ‘in’ keyword is also used in the syntax of other unrelated Python constructions: “for loops” and “list comprehensions.”

77. In in strings and containers • The in keyword checks if the given object is contained within the aggregate. >>> p = “cat” >>> j = [‘cat’, ‘dog’] >>> p in j True >>> ‘a’ in p True >>> ‘t’ in p[:2] False cat

78. Range function • Python has a range function to easily form lists of integers. >>> range(5) [0, 1, 2, 3, 4] [0, 1, 2, 3, 4] >>> range(2,5) [2, 3, 4] [0, 1, 2, 3, 4] >>> range(0, 10, 2) [0, 2, 4, 6, 8] [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(5, 0, -1) [5, 4, 3, 2, 1] Count down

79. • Tuples are defined using parentheses (and commas). The + Operator >>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’) • Lists are defined using square brackets (and commas). >>> li = [“abc”, 34, 4.34, 23] • Strings are defined using quotes (“, ‘, or “““). >>> st = “Hello World” >>> st = ‘Hello World’ • The + operator produces a new tuple, list, or string whose value is the concatenation of its arguments. >>> (1, 2, 3) + (4, 5, 6) ( ) for tuples (1, 2, 3, 4, 5, 6) >>> [1, 2, 3] + [4, 5, 6] [1, 2, 3, 4, 5, 6] [ ] for lists >>> “Hello” + “ ” + “World” “ ” for strings ‘Hello World’

80. The * Operator • The * operator produces a new tuple, list, or string that “repeats” the original content. >>> (1, 2, 3) * 3 (1, 2, 3, 1, 2, 3, 1, 2, 3) >>> [1, 2, 3] * 3 [1, 2, 3, 1, 2, 3, 1, 2, 3] >>> “Hello” * 3 ‘HelloHelloHello’

81.Lists

82. Lists are the most flexible containers • Lists are Python’s most flexible ordered collection object type • Lists can contain any sort of object: • numbers, • strings • and even other lists

83. Lists are ordered places for objects • Ordered collections of arbitrary objects 1.from the functional view, lists are just a place to collect other objects 2.Lists also define a left to right positional ordering of the items in the list pointer Pointer to NIL A B [A B [55 A55]] 55 A55 Schemata like this will help us to understand the concepts of mutable and immutable objects

84. Lists are mutable • Ordered collection of data • Data can be of different >>> x = [1,'hello', (3 + 2j)] types >>> x • Lists are mutable [1, 'hello', (3+2j)] • There are issues with shared >>> x[2] references and mutability (3+2j) • Lists have the same subset >>> x[0:2] operations as Strings [1, 'hello']

85. Using lists • Accessed by offset --- you can fetch a component object out of a list by indexing the list on the object’s offset --- you can also use lists for such tasks as slicing and concatenation

86. Declaring Lists • >>> aa=[] #An empty list • >>> aa=[1,2,3,4] #4 items, index 0-3

87.Lists can grow and shrink, have any objects • Variable length, heterogeneous, arbitrary nestable --- Unlike strings, strings list can grow and shrink in place --- lists may contain any sort of object, not just one- character strings (they are heterogeneous) pointer Pointer to NIL A B [A B [55 A55]] 55 A55

88.List in action • List respond to the + and * operations much like strings >>> aa=[1,2,3] >>> bb=[4,5,6] >>> aa+bb >>> aa*3

89.List in action: len and in • Lists also have the function len() to tell the size of lists and “in” function >>> aa=[1,2,3] >>> len(aa) # test of len >>> 3 in aa # test of in

90.Append

91. List method calls The list append method simply tacks a single item onto the end of the list >>> aa=[] Pay attention to this syntax with a dot >>> aa.append(1) [1] >>> aa.append(2) [1, 2] >>> aa.append(3) [1, 2, 3] >>> aa.append(‘4’) [1, 2, 3, ‘4’] >>> aa.append(5.0) [1, 2, 3, ‘4’, 5.0] 1 2 3 ‘4’ 5.0

92. Lists = STACK OF CARDS METAPHOR how to think about them • Think of a list as a stack of cards, cards on which your information is written • The information stays in the order you place it in until you modify that order • Methods: • return a string or subset of the list • or modify the list to add or remove components • Written as var[index], index refers to order within set (think card number, starting at 0) • You can step through lists as part of a loop

93.Summary of important operations on lists. Stack of cards metaphor • Adding to the List • var[n] = object • replaces n with object • var.append(object) • adds object to the end of the list • Removing from the List • var[n] = [] • empties contents of card, but preserves order • var.remove(n) • removes card at n • var.pop(n) • removes n and returns its value

94. More examples of operations on lists • List: • A container that holds a number of other objects, in a given order • Defined in square brackets a = [1, 2, 3, 4, 5] print a[1] # number 2 some_list = [] [] some_list.append("foo") ["foo"] some_list.append(12) ["foo“. 12] print len(some_list) # 2

95. More operators on Lists: del and slices Nested list • a = [98, "bottles of beer", ["on", "the", "wall"]] • Same operators as for strings • a+b, a*3, a[0], a[-1], a[1:], len(a) • Item and slice assignment A list that includes three • a[0] = 98 strings • a[1:2] = ["bottles", "of", "beer"] -> [98, "bottles", "of", "beer", ["on", "the", "wall"]] • del a[-1] # -> [98, "bottles", "of", "beer"] Last element removed

96.More list operations: range, append, pop, insert, reverse, sort >>> a = range(5) # [0,1,2,3,4] >>> a.append(5) # [0,1,2,3,4,5] Pop from end, >>> a.pop() # [0,1,2,3,4] removes from end, 5 returns this value >>> a.insert(0, 5.5) # [5.5,0,1,2,3,4] >>> a.pop(0) # [0,1,2,3,4] Pop from front 5.5 >>> a.reverse() # [4,3,2,1,0] >>> a.sort() # [0,1,2,3,4]

97. List method calls: SORT • The sort function orders a list in place (in ascending fashion) Pay attention to this >>> aa=[4,2,6,8,1,3,4,10] syntax with a dot >>> aa.sort()

98. List method calls: REVERSE and POP • ‘reverse’ reverses the list in-place >>> aa=[1,2,3,4] >>> aa.reverse() • ‘pop’ deletes an item from the end >>> aa.pop()

99. Operations in List  append • Indexing e.g., L[i]  insert • Slicing e.g., L[1:5]  index • Concatenation e.g., L + L  count • Repetition e.g., L * 5  sort • Membership test e.g., ‘a’ in L  reverse • Length e.g., len(L)  remove  pop For you to  extend remember

100. Nested List •List in a list •E.g., >>> s = [1,2,3] >>> t = [‘begin’, s, ‘end’] >>> t [‘begin’, [1, 2, 3], ‘end’] >>> t[1][1] 2 Second element from second element

101. Lists: Modifying Content • x[i] = a reassigns the ith element to the >>> x = [1,2,3] value a >>> y = x >>> x[1] = 15 • Since x and y point to >>> x the same list object, [1, 15, 3] >>> y both are changed [1, 15, 3] • The method append x also modifies the list y 1 2 3 15

102. Lists: Modifying Content • x[i] = a reassigns the >>> x = [1,2,3] ith element to the >>> y = x >>> x[1] = 15 value a >>> x [1, 15, 3] • Since x and y point to >>> y the same list object, [1, 15, 3] both are changed >>> x.append(12) >>> y • The method append [1, 15, 3, 12] x also modifies the list y 1 15 3 12

103.Lists: Modifying Contents >>> x = [1,2,3] >>> y = x >>> z = x.append(12) • The method append >>> z == None modifies the list and True >>> y returns None [1, 2, 3, 12] >>> x = x + [9,10] • List addition (+) >>> x [1, 2, 3, 12, 9, 10] returns a new list >>> y [1, 2, 3, 12] y >>> 1 15 3 12 x 9 1 15 3 12 10

104.Lists in ArcToolbox You will create lists: • Layers as inputs • Attributes to match • Arrays of objects You will work with lists: • List of field names • List of selected features

105.Tupl es

106. Operations on Tuples • Indexing e.g., T[i] • Slicing e.g., T[1:5] • Concatenation e.g., T + T • Repetition e.g., T * 5 • Membership test e.g., ‘a’ in T • Length e.g., len(T)

107. Tuples • Like a list, tuples are iterable arrays of objects • Tuples are immutable – once created, unchangeable • To add or remove items, you must redeclare • Example uses of tuples • County Names • Land Use Codes • Ordered set of functions

108. Pay attention Tuples • Tuples are immutable versions of lists • One strange point is the >>> x = (1,2,3) format to make a tuple with >>> x[1:] We (2, 3) one element: create a >>> y = (2,) tuple >>> y ‘,’ is needed to differentiate (2,) with from the mathematical one >>> element expression (2)

109. Tuples • What is a tuple? • A # sign is a comment. Comments are not tuple # sign is a comment. Comments are not is # sign is a comment. Comments are not an # sign is a comment. Comments are not ordered # sign is a comment. Comments are not collection # sign is a comment. Comments are not which cannot be # sign is a comment. Comments are not modified # sign is a comment. Comments are not once # sign is a comment. Comments are not it # sign is a comment. Comments are not has # sign is a comment. Comments are not been # sign is a comment. Comments are not created. • In # sign is a comment. Comments are not other # sign is a comment. Comments are not words, # sign is a comment. Comments are not it's # sign is a comment. Comments are not a special array, # sign is a comment. Comments are not a read-only array. • How to make a tuple? In round brackets • E.g., >>> t = () >>> t = (1, 2, 3) Not the >>> t = (1, ) same >>> t = 1, >>> a = (1, 2, 3, 4, 5) >>> print a[1] # 2

110.Mutability: Tuples vs. Lists What’s the difference between tuples and lists?

111.Tuples are Immutable We want wrongly to change 4.56 to 3.14 in tuple t >>> t = (23, ‘abc’, 4.56, (2,3), ‘def’) Python >>> t[2] = 3.14 protest s Traceback (most recent call last): File "<pyshell#75>", line 1, in -toplevel- tu[2] = 3.14 TypeError: object doesn't support item assignment You’re not allowed to change a tuple in place in memory; memory so, you can’t just change one element of it. But it’s always OK to make a fresh tuple and assign its reference to a previously used name. >>> t = (1, 2, 3, 4, 5)

112. Lists are Mutable We are allowed by Python to change 23 to 45 because li is a list, not tuple >>> li = [‘abc’, 23, 4.34, 23] >>> li[1] = 45 >>> li [‘abc’, 45, 4.34, 23] We can change lists in place. place So, it’s ok to change just one element of a list. Name li still points to the same memory reference when we’re done.

113.Operations on Lists Only: lists are slower but more flexible • Since lists are mutable (they can be changed in place in memory), there are many more operations we can perform on lists than on tuples. • The mutability of lists also makes managing them in memory more complicated… So, they aren’t as fast as tuples. It’s a tradeoff.

114.Operations on Lists Only: APPENDING AND INSERTING IN LIST li >>> li = [1, 2, 3, 4, 5] >>> li.append(‘a’) >>> li [1, 2, 3, 4, 5, ‘a’] >>> li.insert(2, ‘i’) >>>li [1, 2, ‘i’, 3, 4, 5, ‘a’]

115. More operations on Lists Only The ‘extend’ operation on lists is similar to concatenation with the + operator. • But while the + creates a fresh list (with a new memory reference) containing copies of the members from the two inputs, the extend operates on list li in place. place li [1, 2, ‘i’, 3, 4, 5, ‘a’] >>> li.extend([9, 8, 7]) >>>li [1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7] Extend takes a list as an argument. Append takes a singleton. >>> li.append([9, 8, 7]) We take li as it is after last operation extend above >>> li [1, 2, ‘i’, 3, 4, 5, ‘a’, 9, 8, 7, [9, 8, 7]]

116.More operations on Lists Only >>> li = [‘a’, ‘b’, ‘c’, ‘b’] >>> li.index(‘b’) # index of first occurrence 1 >>> li.count(‘b’) # number of occurrences 2 >>> li.remove(‘b’) # remove first occurrence >>> li [‘a’, ‘c’, ‘b’]

117.Even More operations on Lists Only >>> li = [5, 2, 6, 8] >>> li.reverse() # reverse the list *in place* >>> li [8, 6, 2, 5] >>> li.sort() # sort the list *in place* >>> li [2, 5, 6, 8] This is some comparison function defined by the user >>> li.sort(some_function) # sort in place using user-defined comparison

118. Tuples vs. Lists, conversions • Lists are slower but more powerful than tuples. • Lists can be modified, and they have lots of handy operations we can perform on them. • Tuples are immutable and have fewer features. • We can always convert between tuples and lists using the list() and tuple() functions. li = list(tu) tu = tuple(li)

119.List vs. Tuple • What are common characteristics? • Both store arbitrary data objects • Both are of sequence data type • What are differences? • Tuple doesn’t allow modification • Tuple doesn’t have methods • Tuple supports format strings • Tuple supports variable length parameter in function call. • Tuples slightly faster

120.Dictiona ries

121.Container Types: A reminder • We’ve talked about integers, floats, and strings… • Containers are other built-in data types in Python. • Can hold objects of any type (including their own type). • There are three kinds of containers: Tuples • A simple immutable ordered sequence of items. Lists • Sequence with more powerful manipulations possible. Dictionaries • A look-up table of key-value pairs.

122. Dictionaries • Dictionaries are sets of key & value pairs • Allows you to identify values by a descriptive name instead of order in a list • Keys are unordered unless explicitly sorted • Keys are unique: • var[‘item’] = “apple” • var[‘item’] = “banana” • print var[‘item’] prints just banana

123. Dictionaries {"name":"Guido", "age":43} • Dictionaries: curly brackets • What is dictionary? pairs • Refer value through key; “associative arrays” • Like an array indexed by a string • An unordered set of key: value pairs • Values of any type; keys of almost any type • {"name":"Guido", "age":43, ("hello","world"):1, 42:"yes", "flag": ["red","white","blue"]} d = { "foo" : 1, "bar" : 2 } print d["bar"] # 2 some_dict = {} some_dict["foo"] = "yow!" print some_dict.keys() # ["foo"]

124.Dictionary details • Dictionaries are mutable • Keys must be immutable: • numbers, strings, tuples of immutables • these cannot be changed after creation • reason is hashing (fast lookup technique) • not lists or other dictionaries • these types of objects can be changed "in place" • no restrictions on values • Keys will be listed in arbitrary order • again, because of hashing

125.Dictionaries • A set of key-value pairs >>> d = {1 : 'hello', 'two' : 42, 'blah' : [1,2,3]} >>> d {1: 'hello', 'two': 42, 'blah': [1, 2, 3]} >>> d['blah'] [1, 2, 3]

126. Dictionaries: Add/Modify • Entries can be changed by assigning to that entry >>> d {1: 'hello', 'two': 42, 'blah': [1, 2, 3]} >>> d['two'] = 99 >>> d {1: 'hello', 'two': 99, 'blah': [1, 2, 3]} modify • Assigning to a key that does not exist adds an entry >>> d[7] = 'new entry' >>> d {1: 'hello', 7: 'new entry', 'two': 99, 'blah': [1, 2, 3]} adds

127.Dictionaries: Deleting Elements • The del method deletes an element from a dictionary >>> d {1: 'hello', 2: 'there', 10: 'world'} >>> del(d[2]) >>> d {1: 'hello', 10: 'world'} The whole pair is removed

128. Copying Dictionaries and Lists • The built-in list >>> l1 = [1] >>> d = {1 : 10} function will copy >>> l2 = list(l1) >>> d2 = d.copy() >>> l1[0] = 22 >>> d[1] = 22 a list >>> l1 >>> d [22] {1: 22} • The dictionary has >>> l2 >>> d2 a method called [1] {1: 10} copy d = {1 : 10} copy d2 = {1 : 10} d[1 ]=2 2 d = {1 : 22}

129. Data Type Summary • Integers: 2323, 3234L • Floating Point: 32.3, 3.1E2 • Complex: 3 + 2j, 1j • Lists: l = [ 1,2,3] • Tuples: t = (1,2,3) • Dictionaries: d = {‘hello’ : ‘there’, 2 : 15}

130. Data Type Summary • Lists, Tuples, and Dictionaries can store any type (including other lists, tuples, and dictionaries!) • Only lists and dictionaries are mutable • All variables are references

131.File I/O

132. Files • Files are manipulated by creating a file object • f = open("points.txt", "r") • The file object then has new methods • print f.readline() # prints line from file • Files can be accessed to read or write • f = open("output.txt", "w") • f.write("Important Output!") • Files are iterable objects, like lists

133. open() and file() • These are identical: f = open(filename, "r") f = file(filename, "r") • The open() version is older • The file() version is the recommended way to open a file now • We will be using both

134.We ope crea n a file ting f File I/O file or inpu Name of the file obje t ct f , f = file("foo", "r") We read a line line = f.readline() from file object f print line, ct f.close() ob j e i s file # Can use sys.stdin as input; th close We # Can use sys.stdout as output.

135. Files: Input input = open(‘data’, ‘r’) Open the file for input S = input.read() Read whole file into one String S = input.read(N) Reads N bytes (N >= 1) L = input.readlines() Returns a list of line strings

136. Files: Output output = open(‘data’, ‘w’) Open the file for writing output.write(S) Writes the string S to file output.writelines(L) Writes each of the strings in list L to file output.close() Manual close

137. Files: Input inflobj = open(‘data’, ‘r’) Open the file ‘data’ for input S = inflobj.read() Read whole file into one String S S = inflobj.read(N) Reads N bytes (N >= 1) into S L = inflobj.readlines() Returns a list L of line strings

138. Files: Output outflobj = open(‘data’, ‘w’) Open the file ‘data’ for writing outflobj.write(S) Writes the string S to file outflobj.writelines(L) Writes each of the strings in list L to file outflobj.close() Closes the file

139.User Input • The raw_input(string) string method returns a line of user input as a string • The parameter is used as a prompt • The string can be converted by using the conversion methods int(string), float(string), etc.

140. Input: Example print "What's your name?" name = raw_input("> ") print "What year were you born?" birthyear = int(raw_input("> ")) print "Hi %s! You are %d years old!" % (name, 2011 - birthyear) ~: python input.py What's your name? > Michael What year were you born? >1980 Hi Michael! You are 31 years old!

141. Booleans • 0 and None are false • Everything else is true • True and False are aliases for 1 and 0 respectively

142. Boolean Expressions • and and or return one of the >>> True and False False elements in the expression >>> False or True True >>> 7 and 14 • Note that when None is returned 14 >>> None and 2 the interpreter does not print >>> None or 2 anything 2

143. If Statements import math x = 30 if x <= 15 : >>> import ifstatement y = x + 15 y = 0.999911860107 elif x <= 30 : >>> y = x + 30 else : y=x In interpreter print ‘y = ‘, print math.sin(y) In file ifstatement.py

144. Indentation and Blocks • Python uses whitespace and indents to denote blocks of code • Lines of code that begin a block end in a colon: • Lines within the code block are indented at the same level • To end a code block, remove the indentation • You'll want blocks of code that run only when certain conditions are met

145. Conditional Branching Ends with a colon • if and else if variable == condition: identation #do something based on v == c else: #do something based on v != c • elif allows for additional branching Ends with a colon if condition: Ends with a colon elif another condition: … else: #none of the above

146. While Loops >>> import whileloop x=1 1 while x < 10 : 2 print x 3 x=x+1 4 5 6 7 8 In whileloop.py 9 >>> In interpreter

147.Loopi ng with

148. Looping with For • For allows you to loop over a block of code a set number of times • For is great for manipulating lists: a = ['cat', 'window', 'defenestrate'] for x in a: print x, len(x) Results: cat 3 window 6 defenestrate 12

149.Looping with For • We could use a for loop to perform processing tasks on each layer in a list • We could get a list of features in a feature class and loop over each, checking attributes • Anything in a sequence or list can be used in a For loop • Just be sure not to modify the list while looping

150.Additional Python Resources • Python Homepage http://www.python.org/ • Dive Into Python http://www.diveintopython.org/ • Learning Python, 3rd Edition http://www.oreilly.com/catalog/9780596513986/ • Getting Started Writing Geoprocessing Scripts Available on ESRI's support page

151.Sourc es Matt Huenerfauth Marty Stepp Bernard Chen