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

Slides:



Advertisements
Similar presentations
Container Types in Python
Advertisements

CHAPTER 4 AND 5 Section06: Sequences. General Description "Normal" variables x = 19  The name "x" is associated with a single value Sequence variables:
String and Lists Dr. Benito Mendoza. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list List.
Μαθαίνοντας Python [Κ4] ‘Guess the Number’
Python 2 Some material adapted from Upenn cis391 slides and other sources.
Fundamentals of Python: From First Programs Through Data Structures
VBA Modules, Functions, Variables, and Constants
Introduction to Python
Introduction to Python II CIS 391: Artificial Intelligence Fall, 2008.
Functions in Python. The indentation matters… First line with less indentation is considered to be outside of the function definition. Defining Functions.
CSC 9010: Natural Language Processing
Python Control of Flow.
List Comprehensions. Python’s higher-order functions  Python supports higher-order functions that operate on lists similar to Scheme’s >>> def square(x):
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Introduction to Python
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 2 Input, Processing, and Output.
Introduction to Python I CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005.
Input, Output, and Processing
20-753: Fundamentals of Web Programming 1 Lecture 12: Javascript I Fundamentals of Web Programming Lecture 12: Introduction to Javascript.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
Fall Week 4 CSCI-141 Scott C. Johnson.  Computers can process text as well as numbers ◦ Example: a news agency might want to find all the articles.
Collecting Things Together - Lists 1. We’ve seen that Python can store things in memory and retrieve, using names. Sometime we want to store a bunch of.
Built-in Data Structures in Python An Introduction.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
Data TypestMyn1 Data Types The type of a variable is not set by the programmer; rather, it is decided at runtime by PHP depending on the context in which.
Recap form last time How to do for loops map, filter, reduce Next up: dictionaries.
Introducing Python CS 4320, SPRING Resources We will be following the Python tutorialPython tutorial These notes will cover the following sections.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Python Functions.
1 FUNCTIONS - I Chapter 5 Functions help us write more complex programs.
Chapter 3 Syntax, Errors, and Debugging Fundamentals of Java.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
8-1 Compilers Compiler A program that translates a high-level language program into machine code High-level languages provide a richer set of instructions.
1 Lecture 9 Shell Programming – Command substitution Regular expressions and grep Use of exit, for loop and expr commands COP 3353 Introduction to UNIX.
Introduction to Python Dr. José M. Reyes Álamo. 2 Three Rules of Programming Rule 1: Think before you program Rule 2: A program is a human-readable set.
Jim Havrilla. Invoking Python Just type “python –m script.py [arg]” or “python –c command [arg]” To exit, quit() or Control-D is used To just use the.
1 Printing in Python Every program needs to do some output This is usually to the screen (shell window) Later we’ll see graphics windows and external files.
Python Let’s get started!.
 Control Flow statements ◦ Selection statements ◦ Iteration statements ◦ Jump statements.
CSE 130 : Winter 2009 Programming Languages Lecture 11: What’s in a Name ?
CS190/295 Programming in Python for Life Sciences: Lecture 6 Instructor: Xiaohui Xie University of California, Irvine.
I NTRODUCTION TO PYTHON - GETTING STARTED ( CONT )
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
4 - Conditional Control Structures CHAPTER 4. Introduction A Program is usually not limited to a linear sequence of instructions. In real life, a programme.
1 Python Data Structures LING 5200 Computational Corpus Linguistics Martha Palmer.
String and Lists Dr. José M. Reyes Álamo. 2 Outline What is a string String operations Traversing strings String slices What is a list Traversing a list.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
String and Lists Dr. José M. Reyes Álamo.
Introduction to Python
Containers and Lists CIS 40 – Introduction to Programming in Python
CS-104 Final Exam Review Victor Norman.
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
Introduction to Python
Python Primer 2: Functions and Control Flow
Topics Introduction to File Input and Output
Sentinel logic, flags, break Taken from notes by Dr. Neil Moore
CS190/295 Programming in Python for Life Sciences: Lecture 6
Python 2 Some material adapted from Upenn cis391 slides and other sources.
PHP.
String and Lists Dr. José M. Reyes Álamo.
CSC1018F: Intermediate Python
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Python Primer 1: Types and Operators
CISC101 Reminders All assignments are now posted.
Topics Introduction to File Input and Output
Introduction to Computer Science
Presentation transcript:

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. 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.

Functions in Python

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

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.

Calling a Function The syntax for a function call is: >>> def myfun(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.

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.

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.

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. >>> def myfun(x): return x*3 >>> def applier(q, x): return q(x) >>> applier(myfun, 7) 21

Some Fancy Function Syntax

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.

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. >>> def myfun(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.

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. >>> def myfun(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

Dictionaries

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.

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

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.

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 {}

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)]

Assignment and Containers

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]

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 container is logically equivalent to False. (Just like None.)

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]

Generating Lists using “List Comprehensions”

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.

List Comprehensions Syntax 1 >>> li = [3, 6, 2, 7] >>> [elem*2 for elem in li] [6, 12, 4, 14] [ expression for name in list ] –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. Note: Non-standard colors on next several slides to help clarify the list comprehension syntax.

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]

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]

Filtered List Comprehension 1 [ expression for name in list if filter ] 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.

Filtered List Comprehension 2 [ expression for name in list if filter ] >>> 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.

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].

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

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.

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

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.

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)

Logical Expressions

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

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.

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.

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.

For Loops

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.

For Loops 1 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 in : When is a list or a tuple, then the loop steps through each element of the container. When is a string, then the loop steps through each character of the string. for someChar in “Hello World”: print someChar Note: Non- standard colors on these slides.

For Loops 2 The part of the for loop can also be more complex than a single variable name. –When the elements of a container are also containers, then the 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

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

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.

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.

Formatting Strings with % >>> x = “abc” >>> y = 34 >>> “%s xyz %d” % (x, y) ‘abc xyz 34’ The tuple following the % operator is used to fill in the blanks in the original string marked with %s or %d. –Check Python documentation for whether to use %s, %d, or some other formatting code inside the string.

Printing with Python You can print a string to the screen using “print.” Using the % string operator in combination with the print command, we can format our output text. >>> print “%s xyz %d” % (“abc”, 34) abc xyz 34 “Print” automatically adds a newline to the end of the string. If you include a list of strings, it will concatenate them with a space between them. >>> print “abc”>>> print “abc”, “def” abcabc def

String Conversions

String to List to String Join turns a list of strings into one string..join( ) >>> “;”.join( [“abc”, “def”, “ghi”] ) “abc;def;ghi” Split turns one string into a list of strings..split( ) >>> “abc;def;ghi”.split( “;” ) [“abc”, “def”, “ghi”] Note: Non-standard colors on this slide to help clarify the string syntax.

Convert Anything to a String The built-in str() function can convert an instance of any data type into a string. –You can define how this function behaves for user-created data types. You can also redefine the behavior of this function for many types. >>> “Hello ” + str(2) “Hello 2”