Introduction to Python Fred L. Drake, Jr.

Slides:



Advertisements
Similar presentations
Python Whats in a name? Snake logos and mascot notwithstanding, its named after Monty Pythons Flying Circus Humor-impaired can safely.
Advertisements

director of PythonLabs at Zope Corporation
Introduction to Python LinuxWorld - New York City - January 2002 Guido van Rossum Director of PythonLabs at Zope Corporation
Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
10/10/1999© 1999 CNRI, Guido van Rossum 1 Python Workshop Guido van Rossum CNRI (Corporation for National Research Initiatives, Reston, Virginia,
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.
Programming Languages and Paradigms
A Crash Course Python. Python? Isn’t that a snake? Yes, but it is also a...
Portability and Safety Mahdi Milani Fard Dec, 2006 Java.
Python Tidbits Python created by that guy ---> Python is named after Monty Python’s Flying Circus 1991 – Python Released 2008 – Python 2.6 / 3.0rc2.
George Blank University Lecturer. CS 602 Java and the Web Object Oriented Software Development Using Java Chapter 4.
Introduction to Python. Outline Python IS ……. History Installation Data Structures Flow of Control Functions Modules References.
C. Varela, Adapted with permission from Guido van Rossum1 Python Intro, Concurrency Carlos Varela RPI Adapted with permission from: Guido van Rossum
1 Outline 7.1 Introduction 7.2 Implementing a Time Abstract Data Type with a Class 7.3 Special Attributes 7.4Controlling Access to Attributes 7.4.1Get.
CIT 590 Intro to Programming First lecture on Java.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 25 – Perl and CGI (Common Gateway Interface) Outline 25.1 Introduction 25.2 Perl 25.3 String Processing.
GlueTrack interpreter for S2E beam dynamic simulations Igor Zagorodnov BDGM, DESY
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
Introduction to Scripting Languages: Python Some slides are based upon Python Documentation - Extended.
Introduction to Python LinuxWorld - New York City - January 2002 Guido van Rossum Director of PythonLabs at Zope Corporation (Now with: Google Inc.)
1 Programming in Python Language Overview. 2 Who is using it? Google (various projects) NASA (several projects) NYSE (one of only three languages "on.
1 JavaScript. 2 What’s wrong with JavaScript? A very powerful language, yet –Often hated –Browser inconsistencies –Misunderstood –Developers find it painful.
Python Guido van Rossum Sung-Jin Hong SPARCS
1 Python CIS*2450 Advanced Programming Concepts Material for this lecture was developed by Dr. D. Calvert.
Ruby! Ronald L. Ramos. What is Ruby? Ruby is a scripting language designed by Yukihiro Matsumoto, also known as Matz. It runs on a variety of platforms,
H3D API Training  Part 3.1: Python – Quick overview.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
JAVA BASICS: Variables and References SYNTAX, ERRORS, AND DEBUGGING.
Ch 1. A Python Q&A Session Spring Why do people use Python? Software quality Developer productivity Program portability Support libraries Component.
Netprog: Java Intro1 Crash Course in Java. Netprog: Java Intro2 Why Java? Network Programming in Java is very different than in C/C++ –much more language.
CIT 590 Intro to Programming First lecture on Java.
Guide to Programming with Python Chapter One Getting Started: The Game Over Program.
Introduction to Information Security Python. Python motivation Python is to a Hacker what Matlab is to an engineer Lots of built-in modules Lots of 3.
Looping and Counting Lecture 3 Hartmut Kaiser
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.
C++ Programming Basic Learning Prepared By The Smartpath Information systems
Introduction to Python LinuxWorld - New York City - January 2002 Guido van Rossum Director of PythonLabs at Zope Corporation (Now with: Google Inc.)
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
Java Basics Opening Discussion zWhat did we talk about last class? zWhat are the basic constructs in the programming languages you are familiar.
RUBY by Ryan Chase.
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.
PHP vs. Python. Similarities are interpreted, high level languages with dynamic typing are Open Source are supported by large developer communities are.
Python Let’s get started!.
How to execute Program structure Variables name, keywords, binding, scope, lifetime Data types – type system – primitives, strings, arrays, hashes – pointers/references.
CSE 130 : Winter 2009 Programming Languages Lecture 11: What’s in a Name ?
Dr. Abdullah Almutairi Spring PHP is a server scripting language, and a powerful tool for making dynamic and interactive Web pages. PHP is a widely-used,
1 Python K. Naik, M. Raju and S. Bhatkar December 3, 2002 CMSC 631.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Introduction to Scripting Languages: Python Some slides are based upon Python Documentation - Extended.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
A S P. Outline  The introduction of ASP  Why we choose ASP  How ASP works  Basic syntax rule of ASP  ASP’S object model  Limitations of ASP  Summary.
Quiz 1 A sample quiz 1 is linked to the grading page on the course web site. Everything up to and including this Friday’s lecture except that conditionals.
Presented By P.SRIVIDYA 085D1A0552 Programming Language.
11/04/2009 © 1999 CNRI, Guido van Rossum 1 Python Crash Course Original Document : Python Workshop
Zope Concepts - Python scripts Valentin Baciu Finsiel Romania Tirana, 6 June 2005.
Python Programming Unit -1.
CS 330 Class 7 Comments on Exam Programming plan for today:
Ruby: An Introduction Created by Yukihiro Matsumoto in 1993 (named after his birthstone) Pure OO language (even the number 1 is an instance of a class)
Introduction to Python
Python Bryce Boe.
Introduction Python is an interpreted, object-oriented and high-level programming language, which is different from a compiled one like C/C++/Java. Its.
Introduction to Python
Introduction to Python
Introduction to Python
Overview of OOP Terminology
Introduction to Python LinuxWorld - New York City - January 2002
Programming in Python Language Overview
Presentation transcript:

Introduction to Python Fred L. Drake, Jr.

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

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

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

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

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

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

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

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)

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

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

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

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.

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

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

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

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)

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

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

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

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

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

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

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

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

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

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.

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

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

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

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

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

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

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

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

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

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]

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"

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

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

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

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]

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

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"); }

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

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

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

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

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]

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]

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)

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

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

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

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!

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

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

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

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

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

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

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!')

Slide 1©2002 Zope Corporation. All Rights Reserved.