Presentation is loading. Please wait.

Presentation is loading. Please wait.

Introduction to Python Fred L. Drake, Jr.

Similar presentations


Presentation on theme: "Introduction to Python Fred L. Drake, Jr."— Presentation transcript:

1 Introduction to Python Fred L. Drake, Jr. fdrake@acm.org

2 Slide 1©2002 Zope Corporation. All Rights Reserved. Overview What is Python? Why use Python? Compared to Other Languages Basic Tutorial

3 Slide 1©2002 Zope Corporation. All Rights Reserved. What is Python?

4 Slide 1©2002 Zope Corporation. All Rights Reserved. What is Python? Object-oriented rapid prototyping language Excellent scripting language Also a solid application language Extensible C/C++/Fortran/whatever Java (using Jython or JPE) Embeddable

5 Slide 1©2002 Zope Corporation. All Rights Reserved. “Good citizen” stuff Open source Copyrighted but use is not restricted Development on SourceForge Mature (11 years old) Great user community Many books, & more to come Newsgroups: comp.lang.python, comp.lang.python.announce

6 Slide 1©2002 Zope Corporation. All Rights Reserved. High-level properties Elegant & easy to learn “Executable pseudo-code” Suitable as a first language Extremely portable Linux, Unix, Mac OS, PalmOS, OS/2, BeOS, Amiga, VMS, Cray, OS/390,... Sorry(!): Windows, WinCE, PocketPC

7 Slide 1©2002 Zope Corporation. All Rights Reserved. High-level properties, cont. Compiled to interpreted byte code Compilation is implicit and automatic Byte code is higher-level than Java byte code, so performance is better for most applications Automatic memory management Reference counting Predictable object destruction Amortized cost for reclamation Cycle detector for circular references

8 Slide 1©2002 Zope Corporation. All Rights Reserved. Safety Even security people won't talk about safety, why is it here? What we mean is: Errors in Python code do not cause core dumps (“GPF” on that other O/S) Running out of virtual memory or recursing infinately raises an exception the application can handle

9 Slide 1©2002 Zope Corporation. All Rights Reserved. Interfaces to... Many GUI libraries Platform independent Tk, wxWindows, GTK, Qt AWT, Swing (using Jython or JPE) Platform dependent SVGAlib, Mac OS, X11/Motif, MFC Open source and commercial databases Java (using Jython or JPE)

10 Slide 1©2002 Zope Corporation. All Rights Reserved. Language properties ● Everything is an object ● Modules, functions, classes ● Dynamic typing, polymorphism ● Exception handling ● Static lexical scoping ● Operator overloading ● And...

11 Slide 1©2002 Zope Corporation. All Rights Reserved. Indentation! ● But... ● C/C++/Perl/sh/whatever don't do that! ● So why break with “tradition” ? ● Why do you have it in for {curly braces} ? ● People indent anyway ● Python is for people

12 Slide 1©2002 Zope Corporation. All Rights Reserved. Indentation in Python ● Indentation is used to indicate structure ● Just like in documents, white space is used to aid navigation by the reader ● Just as in a C program, programmer's use white space to aid understanding ● int main(int argc, char *argv[]) { if (argc > 1) printf("Found %d arguments.\n", argc - 1); else printf("No command-line arguments.\n"); return 0; }

13 Slide 1©2002 Zope Corporation. All Rights Reserved. High-level data types Numbers: int, long, float, complex Strings: immutable, both 8-bit and Unicode Containers: lists and dictionaries Large library: binary data, sockets, regular expressions, Web protocol connections Extensions: modules can define new types in Python, C, C++, whatever.

14 Slide 1©2002 Zope Corporation. All Rights Reserved. Why use Python?

15 Slide 1©2002 Zope Corporation. All Rights Reserved. Productivity! ● Reduced development time ● Code is 2-10x shorter than C/C++/Java ● Improved program maintenance ● Code is extremely readable ● Less training ● Python is easy to learn

16 Slide 1©2002 Zope Corporation. All Rights Reserved. What is it used for? Rapid prototyping Web scripting Ad-hoc programming Steering scientific applications XML processing Database applications GUI applications Extension language

17 Slide 1©2002 Zope Corporation. All Rights Reserved. Who uses Python? Zope Corporation (Web application server) RedHat (installation tools) LANL, LLNL, Fermilab (steering) ObjectDomain (extensible UML tool) Industrial Light & Magic (everything) Yahoo! Groups (formerly eGroups) Google (many adjunct services)

18 Slide 1©2002 Zope Corporation. All Rights Reserved. Exciting applications Zope – supercharged Web sites Mailman – GNU mailing list manager Jython – 100% Pure Java implementation XML processing Gnome/KDE scripting Star Wars, Episode 1 ! Can do “Windows stuff” too (COM, ASP,...) Mozilla XPCOM support

19 Slide 1©2002 Zope Corporation. All Rights Reserved. Typical Success Stories Prototype in Python First to market Acquisition Re-write in C++/Java e-shop (now MS Commerce Server), 411 (now Yahoo! Mail) Steering Symbiosis of Python and C++ or Java LANL, LLNL, ILM, Hubble Space Telescope

20 Slide 1©2002 Zope Corporation. All Rights Reserved. How far we've come... 1995: “Python? What's that?”

21 Slide 1©2002 Zope Corporation. All Rights Reserved. How far we've come... 1995: “Python? What's that?” 1997: “But nobody else uses Python!”

22 Slide 1©2002 Zope Corporation. All Rights Reserved. How far we've come... 1995: “Python? What's that?” 1997: “But nobody else uses Python!” 1999: “Where can I hire Python programmers?

23 Slide 1©2002 Zope Corporation. All Rights Reserved. Compared to Other Languages

24 Slide 1©2002 Zope Corporation. All Rights Reserved. Python vs. Perl Easier to learn Important for occasional users More readable code Easier maintenance Fewer “magical” side effects More modular, better for large projects Better Java integration Less Unix bias

25 Slide 1©2002 Zope Corporation. All Rights Reserved. Python vs. Tcl Object oriented More differentiated syntax Less need for C extensions Extensions can't redefine syntax Hence fewer extension conflicts Better Java integration Python uses Tk as de-facto GUI standard

26 Slide 1©2002 Zope Corporation. All Rights Reserved. Python vs. Java Code is 5-10x more concise Dynamic typing Much quicker development No explicit compilation phase Less typing Have your cake & eat it too: Jython – 100% Pure Java Python interpreter JPE – Call Java from Python using the JNI

27 Slide 1©2002 Zope Corporation. All Rights Reserved. Jython Seamless integration with Java Separate implementation Implements the same language Different set of standard modules But lots of overlap Differences in some “grey areas” Some introspection is different Command line options, etc.

28 Slide 1©2002 Zope Corporation. All Rights Reserved. Java Integration Interactive Create & use Java objects interactively Great for testing Java code Compiles directly to Java byte code Create class files from Python code Run as applet in browsers Import Java class files directly Subclass Java classes Pass instances back to Java

29 Slide 1©2002 Zope Corporation. All Rights Reserved. Basic Tutorial

30 Slide 1©2002 Zope Corporation. All Rights Reserved. Tutorial Outline Shell (numbers, strings, variables) Lists (arrays), dictionaries (hashes) Variable semantics Control structures & functions Classes & methods Standard library

31 Slide 1©2002 Zope Corporation. All Rights Reserved. Interactive “Shell” Great for: Learning the language Experimenting with the library Testing your own modules

32 Slide 1©2002 Zope Corporation. All Rights Reserved. Interactive Example ● Type statements or expressions at the prompt: ● >>> print "Hello, world" Hello, world >>> x = 12 ** 2 >>> x / 2 72 >>> # this is a comment

33 Slide 1©2002 Zope Corporation. All Rights Reserved. Numbers The usual notations and operators 12, 3.14, 0xFF, 0377, (-1 + 2) * 3 / 4**5, abs(x), 0 < x <= 5 C-style shifting & masking 1 << 16, x & 0xff, x | 1, ~x, x ^ y Integer division truncates 1 / 2 --> 0 # float(1) / 2 --> 0.5

34 Slide 1©2002 Zope Corporation. All Rights Reserved. Numbers, cont. Long (arbitrary precision) 2L ** 100 --> 1267650600228229401496703205376L Starting in Python 2.2: 2 ** 100 --> 1267650600228229401496703205376L Complex 1j ** 2 --> (-1+0j)

35 Slide 1©2002 Zope Corporation. All Rights Reserved. Strings

36 Slide 1©2002 Zope Corporation. All Rights Reserved. Lists ● a = [99, 'bottles of beer', ['on', 'the wall']] ● Flexible arrays, not linked lists ● Same operators as for strings ● a + b, a * 3, a[0], a[-1], a[1:], len(a) ● Item and slice assignment ● A[0] = 98 a[1:2] = ['bottles', 'of', 'beer'] --> [98, 'bottles', 'of', 'beer', ['on', 'the wall']]

37 Slide 1©2002 Zope Corporation. All Rights Reserved. More list operations >>> a = range(5) # [0, 1, 2, 3, 4] >>> a.append(5) # [0, 1, 2, 3, 4, 5] >>> a.pop() # [0, 1, 2, 3, 4] 5 >>> a.insert(0, 5.5) # [5.5, 0, 1, 2, 3, 4] >>> a.pop(0) # [0, 1, 2, 3, 4] 5.5 >>> a.reverse() # [4, 3, 2, 1, 0] >>> a.sort() # [0, 1, 2, 3, 4]

38 Slide 1©2002 Zope Corporation. All Rights Reserved. Dictionaries ● Hash tables, associative arrays ● d = {"duck": "bird", "water": "liquid"} ● Lookup: ● d["duck"] # --> "bird" d["back"] # raises KeyError exception ● Delete, insert, overwrite: ● del d["water"] d["dirt"] = "solid" d["duck"] = "wet bird"

39 Slide 1©2002 Zope Corporation. All Rights Reserved. More dictionary operations ● Keys, values, items: ● d.keys() --> ['duck', 'water', 'dirt'] d.values() --> ['wet bird', 'liquid', 'solid'] d.items() -->[('duck', 'wet bird'), ('water', 'liquid'), ('dirt', 'solid')] ● Presence check: ● d.has_key('duck') --> 1 d.has_key('spam') --> 0 'duck' in d --> 1

40 Slide 1©2002 Zope Corporation. All Rights Reserved. More about dictionaries ● Values of any type, keys of many types: ● {'name': 'Fred', 'age': 36, # IIRC... ('hello', 'world'): 1, 42: 'yes!', 'flag': ['red', 'white', 'blue'], } ● Keys cannot be mutable objects (like lists or dictionaries) ● Values can be anything at all ● Contents are not ordered

41 Slide 1©2002 Zope Corporation. All Rights Reserved. Variables ● No need to declare ● Assign to initialize ● Use of unassigned variable raises exception ● Not typed ● if friendly: greeting = 'Hello, world' else: greeting = 12 ** 2 print greeting ● Everything is stored as a variable ● Functions, modules, classes

42 Slide 1©2002 Zope Corporation. All Rights Reserved. Reference semantics Assignment manipulates references x = y does not make a copy of y X = y makes x reference the object y references Very useful, but beware! Example: >>> a = [1, 2, 3] >>> b = a >>> a.append(4) >>> print b [1, 2, 3, 4]

43 Slide 1©2002 Zope Corporation. All Rights Reserved. Control structures if condition: statements [ elif condition: statements ] [ else: statements ] while condition: statements [ else: statements ] for var in sequence: statements [ else: statements ] break continue

44 Slide 1©2002 Zope Corporation. All Rights Reserved. Structural indentation for i in range(20): if i % 3 == 0: print i if i % 5 == 0: print 'Bingo!' print '---' for (i = 0; i < 20; ++i) { if (i % 3 == 0) { printf("%d\n", i); if (i % 5 == 0) { printf("Bingo!\n"); } } printf("---\n"); }

45 Slide 1©2002 Zope Corporation. All Rights Reserved. Functions def name(arg1, arg2,...): "documentation" # optional statements return # no value return expression

46 Slide 1©2002 Zope Corporation. All Rights Reserved. Example Function def gcd(a, b): "Return greatest common divisor." while a != 0: a, b = b % a, a # parallel assignment return b >>> print gcd.__doc__ Return greatest common divisor. >>> gcd(12, 20) 4

47 Slide 1©2002 Zope Corporation. All Rights Reserved. Classes class MyClass: "documentation" statements class MyClass(BaseClass1, BaseClass2): "documentation" statements def method(self, arg1, arg2,...): pass classvar = 42

48 Slide 1©2002 Zope Corporation. All Rights Reserved. Example Class class Stack: def __init__(self): self.items = [] def push(self, x): self.items.append(x) def pop(self): # what happens when list is empty? return self.items.pop() def empty(self): return len(self.items) == 0

49 Slide 1©2002 Zope Corporation. All Rights Reserved. Using Classes Creating instances: x = Stack() Using an instance: x.empty() # --> 1 x.push(1) x.empty() # --> 0 x.push("hello!") x.pop() # --> "hello!" Checking instance variables: x.items # --> [1]

50 Slide 1©2002 Zope Corporation. All Rights Reserved. Subclassing class FancyStack(Stack): """Stack with the ability to inspect inferior stack items.""" def peek(self, n): """peek(0) returns top, peek(-1) returns item below that, etc.""" size = len(self.items) assert 0 <= n < size return self.items[size-1-n]

51 Slide 1©2002 Zope Corporation. All Rights Reserved. More Subclassing class LimitedStack(FancyStack): "FancyStack with size limit." def __init__(self, limit): self.limit = limit # Call the base constructor FancyStack.__init__(self) def push(self, x): assert len(self.items) < self.limit # Call base class to do the work FancyStack.push(self, x)

52 Slide 1©2002 Zope Corporation. All Rights Reserved. Class & Instance Variables class Connection: verbose = 0 def __init__(self, host): self.host = host def set_debug(self, v): # make 'verbose' an instance variable self.verbose = v def connect(self): # class or instance doesn't matter! if self.verbose: print 'connecting to', self.host...

53 Slide 1©2002 Zope Corporation. All Rights Reserved. Instance Variable Rules Use of an instance variable, search order: – Instance – Class – Base classes On assignment, always make an instance variable Class variables provide “defaults” for instance variables

54 Slide 1©2002 Zope Corporation. All Rights Reserved. Class Variable Caveats Mutable class variables: – One copy shared by all instances Mutable instance variables: – Separate copy for each instance Can lead to surprises if you're not careful

55 Slide 1©2002 Zope Corporation. All Rights Reserved. Careless Use of Class Variables >>> class Thing:... stuff = []... def addStuff(self, x):... self.stuff.append(x)... >>> t1 = Thing() >>> t2 = Thing() >>> t1.addStuff(42) >>> print t2.stuff [42] Probably not what you wanted!

56 Slide 1©2002 Zope Corporation. All Rights Reserved. Modules Collection of definitions in foo.py file – Functions, classes, variables Using Modules: – import os; print os.name – from os import name; print name Rename after import: – import Tkinter; Tk = Tkinter; del Tkinter – # new in Python 2.2: import Tkinter as Tk

57 Slide 1©2002 Zope Corporation. All Rights Reserved. Packages Collection of modules in a directory Must have __init__.py file – Provides package initialization May contain subpackages Import syntax: – import P.Q.M; print P.Q.M.foo() from P.Q import M; print M.foo() from P.Q.M import foo; print foo()

58 Slide 1©2002 Zope Corporation. All Rights Reserved. Error Handling Uses exceptions, like many other languages Many standard exceptions provided Programmer can define new exceptions Exceptions are defined as classes

59 Slide 1©2002 Zope Corporation. All Rights Reserved. Catching Exceptions try: f = open('story.txt') except IOError, e: print 'Could not open file:', e else: print 'Once upon a time...' print f.read()

60 Slide 1©2002 Zope Corporation. All Rights Reserved. Ensuring Cleanup Operations f = open('somefile.dat') try: process_file(f) finally: f.close() # always executed print 'Done.' # executed on success only

61 Slide 1©2002 Zope Corporation. All Rights Reserved. Raising Exceptions raise IndexError raise IndexError, 'k out of range' raise IndexError('k out of range') try: something except: print 'Oops!' raise

62 Slide 1©2002 Zope Corporation. All Rights Reserved. Defining Exceptions class ParseError(Exception): def __init__(self, lineno, offset, msg): self.lineno = lineno self.offset = offset self.message = msg def __str__(self): return '%s (line %d, character %d)' \ % (self.message, self.lineno, self.offset) def parseFile(f):... if something_isnt_right: raise ParseError(lineno, offset, 'Found vile curly bracket!')

63 Slide 1©2002 Zope Corporation. All Rights Reserved. http://starship.python.net/~fdrake/


Download ppt "Introduction to Python Fred L. Drake, Jr."

Similar presentations


Ads by Google