- 快召唤伙伴们来围观吧
- 微博 QQ QQ空间 贴吧
- 文档嵌入链接
- 复制
- 微信扫一扫分享
- 已成功复制到剪贴板
16 Python_ Assignments
展开查看详情
1 .Understand ing Assignment
2 .Names and References • Python has no pointers like C or C++. Instead, it has “names” and “references”. (Works a lot like Lisp or Java.) • You create a name the first time it appears on the left side of an assignment expression: x = 3 • Names store “references” which are like pointers to locations in memory that store a constant or some object. • Python determines the type of the reference automatically based on what data is assigned to it. • It also decides when to delete it via garbage collection after any names for the reference have passed out of scope.
3 .Names and References 2 • There is a lot going on when we type: x = 3 • First, an integer 3 is created and stored in memory. • A name x is created. • An reference to the memory location storing the 3 is then assigned to the name x. Name: x Type: Ref: <address1> Integer Data: 3 name list memory
4 .Names and References 3 • The data 3 we created is of type integer. In Python, the basic datatypes integer, float, and string are “immutable.” • This doesn’t mean we can’t change the value of x… For example, we could increment x. >>> x = 3 >>> x = x + 1 >>> print x 4
5 .Names and References 4 • If we increment x, then what’s really happening is: • The reference of name x is looked up. • The value at that reference is retrieved. • The 3+1 calculation occurs, producing a new data element 4 which is assigned to a fresh memory location with a new reference. • The name x is changed to point to this new reference. • The old data 3 is garbage collected if no name still refers to it. Type: Name: x Integer Ref: <address1> Data: 3
6 .Names and References 4 • If we increment x, then what’s really happening is: • The reference of name x is looked up. • The value at that reference is retrieved. • The 3+1 calculation occurs, producing a new data element 4 which is assigned to a fresh memory location with a new reference. • The name x is changed to point to this new reference. • The old data 3 is garbage collected if no name still refers to it. Type: Name: x Integer Ref: <address1> Data: 3 Type: Integer Data: 4
7 .Names and References 4 • If we increment x, then what’s really happening is: • The reference of name x is looked up. • The value at that reference is retrieved. • The 3+1 calculation occurs, producing a new data element 4 which is assigned to a fresh memory location with a new reference. • The name x is changed to point to this new reference. • The old data 3 is garbage collected if no name still refers to it. Type: Name: x Integer Ref: <address2> Data: 3 Type: Integer Data: 4
8 .Names and References 4 • If we increment x, then what’s really happening is: • The reference of name x is looked up. • The value at that reference is retrieved. • The 3+1 calculation occurs, producing a new data element 4 which is assigned to a fresh memory location with a new reference. • The name x is changed to point to this new reference. • The old data 3 is garbage collected if no name still refers to it. Name: x Ref: <address2> Type: Integer Data: 4
9 .Assignment 1 • So, for simple built-in datatypes (integers, floats, strings), assignment behaves as you would expect: >>> x = 3 # Creates 3, name x refers to 3 >>> y = x # Creates name y, refers to 3. >>> y = 4 # Creates ref for 4. Changes y. >>> print x # No effect on x, still ref 3. 3
10 .Assignment 1 • So, for simple built-in datatypes (integers, floats, strings), assignment behaves as you would expect: >>> x = 3 # Creates 3, name x refers to 3 >>> y = x # Creates name y, refers to 3. >>> y = 4 # Creates ref for 4. Changes y. >>> print x # No effect on x, still ref 3. 3 Name: x Ref: <address1> Type: Integer Data: 3
11 .Assignment 1 • So, for simple built-in datatypes (integers, floats, strings), assignment behaves as you would expect: >>> x = 3 # Creates 3, name x refers to 3 >>> y = x # Creates name y, refers to 3. >>> y = 4 # Creates ref for 4. Changes y. >>> print x # No effect on x, still ref 3. 3 Name: x Ref: <address1> Type: Integer Data: 3 Name: y Ref: <address1>
12 .Assignment 1 • So, for simple built-in datatypes (integers, floats, strings), assignment behaves as you would expect: >>> x = 3 # Creates 3, name x refers to 3 >>> y = x # Creates name y, refers to 3. >>> y = 4 # Creates ref for 4. Changes y. >>> print x # No effect on x, still ref 3. 3 Name: x Ref: <address1> Type: Integer Data: 3 Name: y Type: Ref: <address1> Integer Data: 4
13 .Assignment 1 • So, for simple built-in datatypes (integers, floats, strings), assignment behaves as you would expect: >>> x = 3 # Creates 3, name x refers to 3 >>> y = x # Creates name y, refers to 3. >>> y = 4 # Creates ref for 4. Changes y. >>> print x # No effect on x, still ref 3. 3 Name: x Ref: <address1> Type: Integer Data: 3 Name: y Type: Ref: <address2> Integer Data: 4
14 .Assignment 1 • So, for simple built-in datatypes (integers, floats, strings), assignment behaves as you would expect: >>> x = 3 # Creates 3, name x refers to 3 >>> y = x # Creates name y, refers to 3. >>> y = 4 # Creates ref for 4. Changes y. >>> print x # No effect on x, still ref 3. 3 Name: x Ref: <address1> Type: Integer Data: 3 Name: y Type: Ref: <address2> Integer Data: 4
15 .Assignment 2 • For other data types (lists, dictionaries, user-defined types), assignment works differently. • These datatypes are “mutable.” • When we change these data, we do it in place. • We don’t copy them into a new memory address each time. • If we type y=x and then modify y, both x and y are changed! • We’ll talk more about “mutability” later. >>> x = 3 x = some mutable object immutable >>> y = x y=x mutable >>> y = 4 make a change to y >>> print x look at x 3 x will be changed as well
16 .More About Assignment Classes, Functions, Naming Rules
17 .Assignment & Mutability 1 • Remember that assignment works differently for mutable vs. immutable datatypes. datatypes • If you type y=x, then changing y: …will change x if they are mutable. …won’t change x if they are immutable. immutable immutable mutable >>> x = 3 >>> x = [ 1, 2, 3] >>> y = x >>> y = x >>> y = y + 1 >>> y.reverse() >>> print x >>> print x 3 [ 3, 2, 1]
18 .Assignment & Mutability 2 Python is object-oriented, and user-defined classes are mutable. Let’s say that the name x refers to an object of some class. This class has a “set” and a “get” function for some value. >>> x.getSomeValue() 4 What happens if we create a new name y and set y=x ? >>> y = x This creates a new name y which points to the same memory reference as the name x. Now, if we make some change to y, then x will be affected as well. >>> y.setSomeValue(3) >>> y.getSomeValue() 3 >>> x.getSomeValue() 3
19 .Assignment & Mutability 3 • When passing parameters to functions: • Immutable data types are “call by value.” • Mutable data types are “call by reference.” • If you pass mutable data to a function, and you change it inside that function, the changes will persist after the function returns. • Immutable data appear unchanged inside of functions to which they are passed.
20 .Naming Rules • Names are case sensitive and cannot start with a number. They can contain letters, numbers, and underscores. bob Bob _bob _2_bob_ bob_2 BoB • There are some reserved words: and, assert, break, class, continue, def, del, elif, else, except, exec, finally, for, from, global, if, import, in, is, lambda, not, or, pass, print, raise, return, try, while
21 .Accessing Non-Existent Name • If you try to access a name before it’s been properly created (by placing it on the left side of an assignment), you’ll get an error. >>> y Traceback (most recent call last): File "<pyshell#16>", line 1, in -toplevel- y NameError: name ‘y' is not defined >>> y = 3 >>> y 3
22 .Multiple Assignment • You can also assign to multiple names at the same time. >>> x, y = 2, 3 >>> x 2 >>> y 3
23 .RANDOM NUMBERS random.randint(0, len(who) - 1)], EXAMPLE who[random.randint(0, len(who) - 1)], # selects random element from list who
24 .Python code from Leila for Cartesian Product to create sentences import random # we have to import random as we are using random number generator def add_to_list(part): # for example , we have add_to_list(who) print(part) # prints the old part of the whole sentence print('Please add a sentence segment.') add_to_string = input() #reads from input a string that …. part.append(add_to_string) # adds more choices to part print(part) # prints the new part of the whole sentence who = ['President Obama', 'Professor Perkowski', 'A pink fluffy unicorn', 'Makana Burch', 'A two-toed sloth', 'Cinderella'] # choices for question “who”, this is called part what = ['is jumping on the bed', 'is party rocking', 'is coding in python', 'is running a marathon', 'is taking over the world', 'is going on a road trip', 'is doing trigonometry homework'] when = ['two thousand years ago', 'forty-eight years from now', 'right in this very millisecond', 'when pigs fly', 'when the cows come home', 'at dawn seven hundred days from now'] where = ['in egypt', 'in your bedroom', 'in a galaxy far far away', 'in Moscow', 'right here in this room', 'in your english teacher`s brain'] why = ['so that he/she can go to bed.', 'so that the apocalypse will be prevented.', 'so that he/she can eat lunch.', 'because if he/she does not, your pet goldfish will rise up and kill you.', 'because he/she needs to save the Queen of Azerbaijan.']
25 .while True: print('Welcome to the random sentence generator!') print("Press 'G' to generate, and press 'ADD' to add to the sentence database, and press E to exit (as if you have something better to do!).") answer = input() answer = answer.upper() # changes to upper case charcters if answer == 'G': print(who[random.randint(0, len(who) - 1)], what[random.randint(0, len(what) - 1)], when[random.randint(0, len(when) - 1 )], where[random.randint(0, len(where) - 1)], why[random.randint(0, len(why) - 1)]) elif answer == 'ADD': print('What list would you like to add to? Your options are Who, What, When, Where, or Why.') answer = input() answer = answer.upper() if answer == 'WHO': # if answer is WHO we add to the list for who add_to_list(who) # we use function add_to_list elif answer == 'WHAT': add_to_list(what) elif answer == 'WHEN': add_to_list(when) elif answer == 'WHERE': add_to_list(where) elif answer == 'WHY': add_to_list(why) elif answer == 'E': print('Goodbye and good riddance!') break; else: print('Computers are so much better than humans. Fix your error, please.')
26 .Why Python?
27 . Languages • Some influential ones: • FORTRAN • science / engineering • COBOL • business data • LISP • logic and AI • BASIC • a simple language 27
28 .Why do people use Python? • Software Quality • Developer productivity • Program portability • Support Libraries
29 .Why do people use Python? • Software Quality: Python is designed to be readable, and hence maintainable. • Developer productivity: Python code is typically 1/3 to 1/5 the size of equivalent C++ or JAVA code