A Brief Introduction to Python

Slides:



Advertisements
Similar presentations
Container Types in Python
Advertisements

Python Objects and Classes
Introduction to Python Week 15. Try It Out! Download Python from Any version will do for this class – By and large they are all mutually.
A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
Introduction to Programming Languages and Techniques FULL PYTHON TUTORIAL Last updated 9/1/2014 xkcd.com Slides courtesy of Prof. Mitch Marcus, University.
Lists Introduction to Computing Science and Programming I.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Introduction to Python II CIS 391: Artificial Intelligence Fall, 2008.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Functions in Python. The indentation matters… First line with less indentation is considered to be outside of the function definition. Defining Functions.
Introduction to Python II CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005.
CSC 9010: Natural Language Processing
Introduction to Python (for C++ programmers). Background Information History – created in December 1989 by Guido van Rossum Interpreted Dynamically-typed.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
Python Tutorial Adapted from slides by Prof. Mitch Marcus.
Introduction to Python Lecture 1. CS 484 – Artificial Intelligence2 Big Picture Language Features Python is interpreted Not compiled Object-oriented language.
Introduction to Python Guido van Rossum Director of PythonLabs at Zope Corporation
Python: A Simple Tutorial CIS 530 – Fall 2010  Highly adapted from slides for CIS 530 originally by Prof. Mitch Marcus  I am your course TA (Varun Aggarwala)
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Python: Classes By Matt Wufsus. Scopes and Namespaces A namespace is a mapping from names to objects. ◦Examples: the set of built-in names, such as the.
1 Python CIS*2450 Advanced Programming Concepts Material for this lecture was developed by Dr. D. Calvert.
Programming in Java Unit 2. Class and variable declaration A class is best thought of as a template from which objects are created. You can create many.
Introduction to Python September 26, /10/ Bioinformatics Languages Low-level, compiled languages: C, C++, Java… Pros: performance Cons:
Introduction to Python III CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005.
Introduction to Python I CSE-391: Artificial Intelligence University of Pennsylvania Matt Huenerfauth January 2005.
An Introduction to Python Blake Brogdon. What is Python?  Python is an interpreted, interactive, object-oriented programming language. (from python.org)
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.
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.
C463 / B551 Artificial Intelligence Dana Vrajitoru Python.
Python uses boolean variables to evaluate conditions. The boolean values True and False are returned when an expression is compared or evaluated.
Copyright © 2012 Pearson Education, Inc. Publishing as Pearson Addison-Wesley C H A P T E R 8 Lists and Tuples.
An Introduction. What is Python? Interpreted language Created by Guido Van Rossum – early 90s Named after Monty Python
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Introduction to Python III CIS 391: Artificial Intelligence Fall, 2008.
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
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.
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
 In the java programming language, a keyword is one of 50 reserved words which have a predefined meaning in the language; because of this,
Python I Some material adapted from Upenn cmpe391 slides and other sources.
LECTURE 3 Python Basics Part 2. FUNCTIONAL PROGRAMMING TOOLS Last time, we covered function concepts in depth. We also mentioned that Python allows for.
CSE 130 : Winter 2009 Programming Languages Lecture 11: What’s in a Name ?
LISTS and TUPLES. Topics Sequences Introduction to Lists List Slicing Finding Items in Lists with the in Operator List Methods and Useful Built-in Functions.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
Chapter 9 Introduction to Arrays Fundamentals of Java.
PHP Tutorial. What is PHP PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages.
1 Python Data Structures LING 5200 Computational Corpus Linguistics Martha Palmer.
Winter 2016CISC101 - Prof. McLeod1 CISC101 Reminders Quiz 3 this week – last section on Friday. Assignment 4 is posted. Data mining: –Designing functions.
Quiz 4 Topics Aid sheet is supplied with quiz. Functions, loops, conditionals, lists – STILL. New topics: –Default and Keyword Arguments. –Sets. –Strings.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Object Oriented Programming in Python: Defining Classes
Introduction Python is an interpreted, object-oriented and high-level programming language, which is different from a compiled one like C/C++/Java. Its.
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.
Programming Language Concepts (CIS 635)
Creating and Deleting Instances Access to Attributes and Methods
Python Classes By Craig Pennell.
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Introduction to Python
Python Primer 2: Functions and Control Flow
Introduction to Python
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Python dicts and sets Some material adapted from Upenn cis391 slides and other sources.
Python I Some material adapted from Upenn cmpe391 slides and other sources.
Introduction to Computer Science
Presentation transcript:

A Brief Introduction to Python Slides courtesy of Prof. Mitch Marcus, University of Pennsylvania CIS Dept.

Python Developed by Guido van Rossum in the early 1990s Named after Monty Python Available on eniac Available for download from http://www.python.org

Advantages of Python Faster development: concise syntax, also no lengthy compile/linking steps Portable: programs run on major platforms without change Various built-in types: lists, dictionaries Large collection of support libraries: eg. NumPy for Matlab like programming

Recommended Reading On-line Python tutorials The Python Tutorial (http://docs.python.org/tutorial/) Dense but more complete overview of the most important parts of the language See course homepage for other tutorials PEP 8- Style Guide for Python Code http://www.python.org/dev/peps/pep-0008/ The official style guide to Python, contains many helpful programming tips

Which Python? Python 2.7 NOT Python 3 Current version on Eniac, so we’ll use it Last stable release before version 3 NOT Python 3 Many changes (including incompatible changes) More existing third party software is compatible with Python 2 than Python 3 right now

Python interpreters On eniac GUI – IDLE lannie@ampersand:~> python Python 2.7.2 (default, Aug 19 2011, 20:41:43) [GCC] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>>

A Silly Code Sample (in IDLE) 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

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 (as with printf in C) Logical operators are words (and, or, not) not symbols Simple printing can be done with print. Indentation matters to the meaning of the code: Block structure indicated by indentation The first assignment to a variable creates it. Variable types don’t need to be declared. Python figures out the variable types on its own.

Whitespace is meaningful in Python Use a newline to end a line of code. Use \ when must go to next line prematurely. Block structure is indicated by indentation The first line with less indentation is outside of the block. The first line with more indentation starts a nested block Often a colon appears at the start of a new block. (E.g. for function and class definitions.)

Dynamic typing – the key difference Java: statically typed Variables are declared to refer to objects of a given type Methods use type signatures to enforce contracts Python: dynamic typed Variables come into existence when first assigned to A variable can refer to an object of any type All types are (almost) treated the same way Main drawback: type errors are only caught at runtime

Assignment Binding a variable in Python means setting a name to hold a reference to some object. Assignment creates references, not copies (like Java) A variable is created the first time it appears on the left side of an assignment expression: x = 3 An object is deleted (by the garbage collector) once it becomes unreachable. Dynamic Typing: Names in Python do not have an intrinsic type. Python determines the type of the reference automatically based on what data is assigned to it. BUT Strong Typing: Objects have fixed types.

Objects and types Objects everywhere: Every entity is an object! Strongly typed: Every object has an associated type, which it carries everywhere Built-in object types: Number 10 String “hello”, ‘hello’ List [1, ‘abc’, 44] Tuple (4, 5) Dictionary {‘food’ : ‘something you eat’, ‘lobster’ : ‘an edible, undersea arthropod’ 15: ‘you can’t eat integers!!!’} Files Missing: Arrays!

Sequence types: Tuples, Lists, and Strings

Sequence Types Tuple Strings Immutable A simple immutable ordered sequence of items Immutable: a tuple cannot be modified once created.... Items can be of mixed types, including collection types Strings Immutable Conceptually very much like a tuple Regular strings use 8-bit characters. Unicode strings use 2-byte characters. (All this is changed in Python 3.) List Mutable ordered sequence of items of mixed types

Sequence Types 2 The three sequence types share much of the same syntax and functionality. Tuples >>> tu = (23, ‘abc’, 4.56, (2,3), ‘def’) Lists >>> li = [“abc”, 34, 4.34, 23] Strings >>> st = “Hello World”; st = ‘Hello World’ Accessing individual members of a sequence >>> tu[1] # Second item in the tuple. ‘abc’ Negative lookup: count from right, starting with –1. >>> t[-3] 4.56

Slicing: Return Copy of a Subset >>> t = (23, ‘abc’, 4.56, (2,3), ‘def’) Return a copy of the container starting at the first index, and stopping before the second index. >>> t[1:4] (‘abc’, 4.56, (2,3)) You can also use negative indices when slicing. >>> t[1:-1] Optional argument allows selection of every nth item. >>> t[1:-1:2] (‘abc’, (2,3))

Operations on Lists Only 1 >>> li.append(‘a’) # Note the method syntax >>> li [1, 11, 3, 4, 5, ‘a’] >>> li.insert(2, ‘i’) >>>li [1, 11, ‘i’, 3, 4, 5, ‘a’]

Operations on Lists Only 2 >>> 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’]

Operations on Lists Only 3 >>> li.reverse() # reverse the list *in place* >>> li [8, 6, 2, 5] >>> li.sort() # sort the list *in place* [2, 5, 6, 8] >>> li.sort(some_function) # sort in place using user-defined comparison >>>sorted(li) #return a copy sorted

Dictionaries: a mapping collection type

Creating, accessing & updating dictionaries >>> d = {‘user’:‘bozo’, ‘pswd’:1234} >>> d[‘user’] ‘bozo’ >>> d[‘bozo’] Traceback (innermost last): File ‘<interactive input>’ line 1, in ? KeyError: bozo >>> d[‘user’] = ‘clown’ >>> d {‘user’:‘clown’, ‘pswd’:1234} Assigning to an existing key replaces its value. Dictionaries are unordered & work by hashing

Useful Accessor Methods >>> d = {‘user’:‘bozo’, ‘p’:1234, ‘i’:34} >>> d.keys() # List of current keys [‘user’, ‘p’, ‘i’] >>> d.values() # List of current values. [‘bozo’, 1234, 34] >>> d.items() # List of item tuples. [(‘user’,‘bozo’), (‘p’,1234), (‘i’,34)]

For Loops

For Loops for <item> in <collection>: <statements> <item> can be more complex than a single variable name. for (x, y) in [(a,1), (b,2), (c,3), (d,4)]: print x Range: range(5) returns [0,1,2,3,4] So we can say: for x in range(5): print x xrange() returns an iterator that provides the same functionality more efficiently

List Comprehensions [ expression for name in list ] >>> [elem*2 for elem in li] [6, 12, 4, 14] >>> li = [(‘a’, 1), (‘b’, 2), (‘c’, 7)] >>> [ n * 3 for (x, n) in li] [3, 6, 21]

Computing a sorted list of n-grams from operator import itemgetter def calc_ngram(inputstring, nlen): ngram_list = [inputstring[x:x+nlen] for x in \ xrange(len(inputstring)-nlen+1)] ngram_freq = {} # dict for storing results for n in ngram_list: # collect the distinct n-grams and count if n in ngram_freq: ngram_freq[n] += 1 else: ngram_freq[n] = 1 # human counting numbers start at 1 # set reverse = False to change order of sort (ascending/descending) return sorted(ngram_freq.iteritems(), \ key=itemgetter(1), reverse=True) http://times.jayliew.com/2010/05/20/a-simple-n-gram-calculator-pyngram/

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

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

Functions in Python (Methods later)

No declaration of types of arguments or result Defining Functions Function definition begins with def Function name and its arguments. def get_final_answer(filename): """Documentation String""" line1 line2 return total_counter ... Colon. ‘return’ indicates the value to be sent back to the caller. First line with less indentation is considered to be outside of the function definition. No declaration of types of arguments or result

Function overloading? No. There is no function overloading in Python. Unlike Java, 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. Two different functions can’t have the same name, even if they have different numbers of arguments. But operator overloading – overloading +, ==, -, etc. – is possible using special methods on various classes (see later slides)

Default Values for Arguments You can provide default values for a function’s arguments These arguments are optional when the function is called >>> 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.

Keyword Arguments Functions can be called with arguments out of order These arguments are specified in the call Keyword arguments can be used 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) >>> myfun(2, c=43, b=1)

Classes and Inheritance

Creating a class class roster: course = "cis391" def __init__(self, name, dept): self.student_name = name self.student_dept = dept def print_details(self): print "Name: " + self.student_name print "Dept: " + self.student_dept student1 = roster(”john", "cis") student1.print_details() Called when an object is instantiated Another member function Creating an instance Calling methods of an object

Subclasses A class can extend the definition of another class Allows use (or extension ) of methods and attributes already defined in the previous one. New class: subclass. Original: parent, ancestor or superclass To define a subclass, put the name of the superclass in parentheses after the subclass’s name on the first line of the definition. class ai_student(student): Python has no ‘extends’ keyword like Java. Multiple inheritance is supported.

Redefining Methods Very similar to over-riding methods in Java To redefine a method of the parent class, include a new definition using the same name in the subclass. The old code won’t get executed. To execute the method in the parent class in addition to new code for some method, explicitly call the parent’s version of the method. parentClass.methodName(self, a, b, c) The only time you ever explicitly pass ‘self’ as an argument is when calling a method of an ancestor. So: myOwnClass.methodName(a,b,c)

Constructors: __init__ Very similar to Java Commonly, the ancestor’s __init__ method is executed in addition to new commands. Must be done explicitly You’ll often see something like this in the __init__ method of subclasses: parentClass.__init__(self, x, y) where parentClass is the name of the parent’s class.

Special Built-In Methods and Attributes

Special Methods – Example class student: ... def __repr__(self): return “I’m named ” + self.full_name + “ – age: , ”, self.age ... >>> f = student(“Bob Smith”, 23) >>> print f I’m named Bob Smith – age: 23 >>> f “I’m named Bob Smith – age: 23”

Other Special Methods Used to implement operator overloading Most operators trigger a special method, dependent on class __init__: The constructor for the class. __len__ : Define how len( obj ) works. __copy__: Define how to copy a class. __cmp__ : Define how == works for class. __add__ : Define how + works for class __neg__ : Define how unary negation works for class Other built-in methods allow you to give a class the ability to use [ ] notation like an array or ( ) notation like a function call.

Iterators

Iterators in Python >>> for e in [1,2]: print e 1 2 >>> it = iter(s) >>> it <iterator object at 0x00A1DB50> >>> it.next() (most recent call last): File "<stdin>", line 1, in ? it.next() StopIteration

Class with iterator in Python class Reverse: "Iterator for looping over a sequence backwards" def __init__(self, data): self.data = data self.index = len(data) def next(self): if self.index == 0: raise StopIteration self.index = self.index - 1 return self.data[self.index] def __iter__(self): return self >>> for char in Reverse('spam'): print char m a p s An iterator is any object with a "next" method

Efficient memory usage Eg: File Objects >>> for line in open(“script.py”): ... print(line.upper()) IMPORT SYS PRINT(SYS.PATH) X = 2 PRINT(2 ** 3) instead of >>> for line in open(“script.py”).readlines():

Generators

Generators Defines an iterator with a function Maintains local state automatically def gensquares(N): for i in range(N): yield i ** 2 >>> for i in gensquares(5): print(i) 1 4 9 16

Using generators Merging sequences: def merge(l, r): llen, rlen, i, j = len(l), len(r), 0, 0 while i < llen or j < rlen: if j == rlen or (i < llen and l[i] < r[j]): yield l[i] i += 1 else: yield r[j] j += 1

Using generators >>> g = merge([2,4], [1, 3, 5]) >>> while True: print g.next() 1 2 3 4 5 Traceback (most recent call last): File "<pyshell#73>", line 2, in <module> StopIteration >>> [x for x in merge([1,3,5],[2,4])] [1, 2, 3, 4, 5]

Generators and exceptions >>> g = merge([2,4], [1, 3, 5]) >>> while True: try: print g.next() except StopIteration: print ‘Done’ break 1 2 3 4 5 Done

List Generators ( expression for name in list if filter ) 1 4 9 16 >>> a = (x * x for x in xrange(5)) >>> a >>> <generator object <genexpr> at 0x031A7A80> >>> for x in a: ...: print x ...: 1 4 9 16

A directed graph class >>> d = DiGraph([(1,2),(1,3),(2,4),(4,3),(4,1)]) >>> print d 1 -> 2 1 -> 3 2 -> 4 4 -> 3 4 -> 1 2 1 3 4

A directed graph class >>> d = DiGraph([(1,2),(1,3),(2,4),(4,3),(4,1)]) >>> [v for v in d.search(1)] [1, 2, 4, 3] >>> [v for v in d.search(4)] [4, 3, 1, 2] >>> [v for v in d.search(2)] [2, 4, 3, 1] >>> [v for v in d.search(3)] [3] 2 1 3 4 search method returns a generator for the nodes that can be reached from a given node by following arrows “from tail to head”

The DiGraph constructor 1 3 4 2 class DiGraph: def __init__(self, edges): self.adj = {} for u,v in edges: if u not in self.adj: self.adj[u] = [v] else: self.adj[u].append(v) def __str__(self): return '\n'.join(['%s -> %s'%(u,v) \ for u in self.adj for v in self.adj[u]]) ... >>> d = DiGraph([(1,2),(1,3),(2,4),(4,3),(4,1)]) >>> d.adj {1: [2, 3], 2: [4], 4: [3, 1]} The constructor builds a dictionary (self.adj) mapping each node name to a list of node names that can be reached by following one edge (an “adjacency list”)

The search method 2 1 3 4 # If we haven't already visited this node... class DiGraph: ... def search(self, u, visited=set()): # If we haven't already visited this node... if u not in visited: # yield it yield u # and remember we've visited it now. visited.add(u) # Then, if there are any adjacent nodes... if u in self.adj: # for each adjacent node... for v in self.adj[u]: # search for all nodes reachable from *it*... for w in self.search(v, visited): # and yield each one. yield w `