1 / 55

Introduction to Python II

Introduction to Python II. CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005. Homework 02. Note change in ‘late policy’ for homeworks. Start working on problems D, E, and F.

phong
Télécharger la présentation

Introduction to Python II

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Introduction to Python II CSE-391: Artificial IntelligenceUniversity of Pennsylvania Matt Huenerfauth January 2005

  2. Homework 02 • Note change in ‘late policy’ for homeworks. • Start working on problems D, E, and F. • Next Wednesday, we’re going to talk about object oriented programming in Python. • If you weren’t too comfortable with this part of the language when you read the tutorials online, then you might want to wait to do problems A, B, and C until after next Wednesday’s class.

  3. Functions in Python

  4. Function definition begins with “def.” Function name and its arguments. The keyword ‘return’ indicates the value to be sent back to the caller. Colon. The indentation matters… First line with different indentation is considered to beoutside of the function definition. Defining Functions No header file or declaration of types of function or arguments. • defget_final_answer(filename): • “Documentation String” line1 • line2 • return total_counter

  5. Python and Types Python determines the data types in a program automatically. “Dynamic Typing” But Python’s not casual about types, it enforces them after it figures them out. “Strong Typing” So, for example, you can’t just append an integer to a string. You must first convert the integer to a string itself. x = “the answer is ” # Decides x is string. y = 23 # Decides y is integer. print x + y # Python will complain about this.

  6. Calling a Function • The syntax for a function call is: >>>defmyfun(x, y): return x * y >>> myfun(3, 4) 12 • Parameters in Python are “Call by Assignment.” • Sometimes acts like “call by reference” and sometimes like “call by value” in C++. • Mutable datatypes: Call by reference. • Immutable datatypes: Call by value.

  7. Functions without returns • All functions in Python have a return value, even ones without a specific “return” line inside the code. • Functions without a “return” will give the special value None as their return value. • None is a special constant in the language. • None is used like NULL, void, or nil in other languages. • None is also logically equivalent to False.

  8. Function overloading? No. • There is no function overloading in Python. • Unlike C++, a Python function is specified by its name alone; the number, order, names, or types of its arguments cannot be used to distinguish between two functions with the same name. • So, you can’t have two functions with the same name, even if they have different arguments.

  9. Treating Functions Like Data • Functions are treated like first-class objects in the language… They can be passed around like other data and be arguments or return values of other functions. >>>defmyfun(x): return x*3 >>>defapplier(q, x): return q(x) >>> applier(myfun, 7) 21

  10. Some Fancy Function Syntax

  11. Lambda Notation • Sometimes it is useful to define short functions without having to give them a name: especially when passed as an argument to another function.>>> applier(lambda z: z * 4, 7) 28 • First argument to applier() is an unnamed function that takes one input and returns the input multiplied by four. • Note: only single-expression functions can be defined using this lambda notation. • Lambda notation has a rich history in program language research, AI, and the design of the LISP language.

  12. Default Values for Arguments • You can give default values for a function’s arguments when you define it; then these arguments are optional when you call it. >>>defmyfun(b, c=3, d=“hello”):return b + c >>> myfun(5,3,”hello”) >>> myfun(5,3) >>> myfun(5) All of the above function calls return 8.

  13. The Order of Arguments • You can call a function with some or all of its arguments out of order as long as you specify them (these are called keyword arguments). You can also just use keywords for a final subset of the arguments. >>>defmyfun(a, b, c):return a-b >>> myfun(2, 1, 43) 1 >>> myfun(c=43, b=1, a=2) 1 >>> myfun(2, c=43, b=1) 1

  14. Dictionaries

  15. Basic Syntax for Dictionaries 1 • Dictionaries store a mapping between a set of keys and a set of values. • Keys can be any immutable type. • Values can be any type, and you can have different types of values in the same dictionary. • You can define, modify, view, lookup, and delete the key-value pairs in the dictionary.

  16. Basic Syntax for Dictionaries 2 >>> d = {‘user’:‘bozo’, ‘pswd’:1234} >>> d[‘user’] ‘bozo’ >>> d[‘pswd’] 1234 >>> d[‘bozo’] Traceback (innermost last): File ‘<interactive input>’ line 1, in ? KeyError: bozo

  17. Basic Syntax for Dictionaries 3 >>> d = {‘user’:‘bozo’, ‘pswd’:1234} >>> d[‘user’] = ‘clown’ >>> d {‘user’:‘clown’, ‘pswd’:1234} Note: Keys are unique. Assigning to an existing key just replaces its value. >>> d[‘id’] = 45 >>> d {‘user’:‘clown’, ‘id’:45, ‘pswd’:1234} Note: Dictionaries are unordered. New entry might appear anywhere in the output.

  18. Basic Syntax for Dictionaries 4 >>> d = {‘user’:‘bozo’, ‘p’:1234, ‘i’:34} >>>del d[‘user’] # Remove one. >>> d {‘p’:1234, ‘i’:34} >>> d.clear() # Remove all. >>> d {}

  19. Basic Syntax for Dictionaries 5 >>> d = {‘user’:‘bozo’, ‘p’:1234, ‘i’:34} >>> d.keys() # List of keys. [‘user’, ‘p’, ‘i’] >>> d.values() # List of values. [‘bozo’, 1234, 34] >>> d.items() # List of item tuples. [(‘user’,‘bozo’), (‘p’,1234), (‘i’,34)]

  20. Assignment and Containers

  21. Multiple Assignment with Container Classes • We’ve seen multiple assignment before: >>> x, y = 2, 3 • But you can also do it with containers. • The type and “shape” just has to match. >>> (x, y, (w, z)) = (2, 3, (4, 5)) >>> [x, y] = [4, 5]

  22. Empty Containers 1 • We know that assignment is how to create a name. x = 3 Creates name x of type integer. • Assignment is also what creates named references to containers. >>> d = {‘a’:3, ‘b’:4} • We can also create empty containers: >>> li = [] >>> tu = () >>> di = {} Note: an empty containeris logically equivalent to False. (Just like None.)

  23. Empty Containers 2 Why create a named reference to empty container? You might want to use append or some other list operation before you really have any data in your list. This could cause an unknown name error if you don’t properly create your named reference first. >>> g.append(3) Python complains here about the unknown name ‘g’! >>> g = [] >>> g.append(3) >>> g[3]

  24. Generating Lists using “List Comprehensions”

  25. List Comprehensions • A powerful feature of the Python language. • Generate a new list by applying a function to every member of an original list. • Python programmers use list comprehensions extensively. You’ll see many of them in real code. • The syntax of a “list comprehension” is tricky. • If you’re not careful, you might think it is a for-loop, an ‘in’ operation, or an ‘if’ statement since all three of these keywords (‘for’, ‘in’, and ‘if’) can also be used in the syntax of a list comprehension. • It’s something special all its own.

  26. List Comprehensions Syntax 1 • Note: Non-standard colors on next several slides to help clarify the list comprehension syntax. >>> li = [3, 6, 2, 7] >>> [elem*2 for elem in li] [6, 12, 4, 14] [expressionfornameinlist] • Where expression is some calculation or operation acting upon the variable name. • For each member of the list, we set name equal to that member, calculate a new value using expression, and then we collect these new values into a new list which becomes the return value of the list comprehension.

  27. List Comprehension Syntax 2 • If the original list contains a variety of different types of values, then the calculations contained in the expression should be able to operate correctly on all of the types of list members. • If the members of list are other containers, then the name can consist of a container of names that match the type and “shape” of the list members. >>> li = [(‘a’, 1), (‘b’, 2), (‘c’, 7)] >>> [ n * 3 for (x, n) in li] [3, 6, 21]

  28. List Comprehension Syntax 3 • The expression of a list comprehension could also contain user-defined functions. >>> def subtract(a, b): return a – b >>> oplist = [(6, 3), (1, 7), (5, 5)] >>> [subtract(y, x) for (x, y) in oplist] [-3, 6, 0]

  29. Filtered List Comprehension 1 [expressionfornameinlistiffilter] • Similar to regular list comprehensions, except now we might not perform the expression on every member of the list. • We first check each member of the list to see if it satisfies a filter condition. Those list members that return False for the filter condition will be omitted from the list before the list comprehension is evaluated.

  30. Filtered List Comprehension 2 [expressionfornameinlistiffilter] >>> li = [3, 6, 2, 7, 1, 9] >>> [elem * 2 for elem in li if elem > 4] [12, 14, 18] • Only 6, 7, and 9 satisfy the filter condition. • So, only 12, 14, and 18 are produced.

  31. Nested List Comprehensions • Since list comprehensions take a list as input and they produce a list as output, it is only natural that they sometimes be used in a nested fashion. >>> li = [3, 2, 4, 1] >>> [elem*2 for elem in [item+1 for item in li] ] [8, 6, 10, 4] • The inner comprehension produces: [4, 3, 5, 2]. • So, the outer one produces: [8, 6, 10, 4].

  32. Control of Flow

  33. Control of Flow • There are several Python expressions that control the flow of a program. All of them make use of Boolean conditional tests. • If Statements • While Loops • Assert Statements

  34. If Statements if x == 3: print“X equals 3.” elif x == 2: print“X equals 2.” else: print“X equals something else.” print“This is outside the ‘if’.” Be careful! The keyword ‘if’ is also used in the syntax of filtered list comprehensions.

  35. While Loops x = 3 while x < 10: x = x + 1 print“Still in the loop.” print“Outside of the loop.”

  36. Break and Continue • You can use the keyword break inside a loop to leave the while loop entirely. • You can use the keyword continue inside a loop to stop processing the current iteration of the loop and to immediately go on to the next one.

  37. Assert • An assert statement will check to make sure that something is true during the course of a program. • If the condition if false, the program stops. assert(number_of_players < 5)

  38. Logical Expressions

  39. True and False • True and False are constants in Python. • Generally, True equals 1 and False equals 0. • Other values equivalent to True and False: • False: zero, None, empty container or object • True: non-zero numbers, non-empty objects. • Comparison operators: ==, !=, <, <=, etc. • X and Y have same value: X == Y • X and Y are two names that point to the same memory reference: X is Y

  40. Boolean Logic Expressions • You can also combine Boolean expressions. • True if a is true and b is true: a and b • True if a is true or b is true: a or b • True if a is false: not a • Use parentheses as needed to disambiguate complex Boolean expressions.

  41. Special Properties of And and Or • Actually ‘and’ and ‘or’ don’t return True or False. They return the value of one of their sub-expressions (which may be a non-Boolean value). • X and Y and Z • If all are true, returns value of Z. • Otherwise, returns value of first false sub-expression. • X or Y or Z • If all are false, returns value of Z. • Otherwise, returns value of first true sub-expression.

  42. The “and-or” Trick • There is a common trick used by Python programmers to implement a simple conditional using ‘and’ and ‘or.’result = test and expr1 or expr2 • When test is True, result is assigned expr1. • When test is False, result is assigned expr2. • Works like (test ? expr1 : expr2) expression of C++. • But you must be certain that the value of expr1 is never False or else the trick won’t work. • I wouldn’t use this trick yourself, but you should be able to understand it if you see it in the code.

  43. For Loops

  44. For Loops / List Comprehensions • Python’s list comprehensions and split/join operations let us do things that usually require a for-loop in other programming languages. • In fact, because of all the sophisticated list and string processing tools built-in to Python, you’ll tend to see many fewer for-loops used in Python code. • Nevertheless, it’s important to learn about for-loops. • Be careful! The keywords for and in are also used in the syntax of list comprehensions, but this is a totally different construction.

  45. For Loops 1 Note: Non-standard colors on these slides. • A for-loop steps through each of the items in a list, tuple, string, or any other type of object which the language considers an “iterator.” for <item> in <collection>:<statements> • When <collection> is a list or a tuple, then the loop steps through each element of the container. • When <collection> is a string, then the loop steps through each character of the string. for someChar in “Hello World”: print someChar

  46. For Loops 2 • The <item> part of the for loop can also be more complex than a single variable name. • When the elements of a container <collection> are also containers, then the <item> part of the for loop can match the structure of the elements. • This multiple assignment can make it easier to access the individual parts of each element. for (x, y) in [(a,1), (b,2), (c,3), (d,4)]: print x

  47. For loops and range() function • Since we often want to range a variable over some numbers, we can use the range() function which gives us a list of numbers from 0 up to but not including the number we pass to it. • range(5) returns [0,1,2,3,4] • So we could say:for x in range(5):print x

  48. String Operations

  49. String Operations • We can use some methods built-in to the string data type to perform some formatting operations on strings: >>>“hello”.upper() ‘HELLO’ • There are many other handy string operations available. Check the Python documentation for more.

  50. String Formatting Operator: % • The operator % allows us to build a string out of many data items in a “fill in the blanks” fashion. • Also allows us to control how the final string output will appear. • For example, we could force a number to display with a specific number of digits after the decimal point. • It is very similar to the sprintf command of C.

More Related