Introduction to Python Programming Languages Fall 2002 Adapted from Tutorial by Mark Hammond Skippi-Net, Melbourne, Australia

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

Optional Static Typing Guido van Rossum (with Paul Prescod, Greg Stein, and the types-SIG)
Chapter Modules CSC1310 Fall Modules Modules Modules are the highest level program organization unit, usually correspond to source files and.
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...
 2005 Pearson Education, Inc. All rights reserved Introduction.
Python By Steve Wright. What is Python? Simple, powerful, GP scripting language Simple, powerful, GP scripting language Object oriented Object oriented.
Ruby The Gem of new programming languages. An interpreted scripting language.
Introduction to Python. Outline Python IS ……. History Installation Data Structures Flow of Control Functions Modules References.
CS-341 Dick Steflik Introduction. C++ General purpose programming language A superset of C (except for minor details) provides new flexible ways for defining.
Python Jordan Miller and Lauren Winkleman CS 311 Fall 2011.
Introduction to Python Programming Languages Fall 2003 Adapted from Tutorial by Mark Hammond Skippi-Net, Melbourne, Australia
Guide To UNIX Using Linux Third Edition
About the Presentations The presentations cover the objectives found in the opening of each chapter. All chapter objectives are listed in the beginning.
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.
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 Introduction.
Python 3 Some material adapted from Upenn cis391 slides and other sources.
Programming 101 with Python: an open-source, cross-platform, and fun language By J. Burton Browning, Ed.D. Copyright © J. Burton Browning All rights reserved.
Introduction to Python, COM and PythonCOM Mark Hammond Skippi-Net, Melbourne, Australia
1 Python Control of Flow and Defining Classes LING 5200 Computational Corpus Linguistics Martha Palmer.
 2004 Prentice Hall, Inc. All rights reserved. Chapter 35 – Python Outline 35.1 Introduction First Python Program Python Keywords 35.2 Basic.
General Computer Science for Engineers CISC 106 Lecture 02 Dr. John Cavazos Computer and Information Sciences 09/03/2010.
Introduction to Python Basics of the Language. Install Python Find the most recent distribution for your computer at:
Computer Science 111 Fundamentals of Programming I Overview of Programming.
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.
H3D API Training  Part 3.1: Python – Quick overview.
CMPS 211 JavaScript Topic 1 JavaScript Syntax. 2Outline Goals and Objectives Goals and Objectives Chapter Headlines Chapter Headlines Introduction Introduction.
CS 11 java track: lecture 1 Administrivia need a CS cluster account cgi-bin/sysadmin/account_request.cgi need to know UNIX
An Introduction to Python Blake Brogdon. What is Python?  Python is an interpreted, interactive, object-oriented programming language. (from python.org)
Guide to Programming with Python Chapter One Getting Started: The Game Over Program.
 Pearson Education, Inc. All rights reserved Introduction to Java Applications.
Python – May 11 Briefing Course overview Introduction to the language Lab.
Built-in Data Structures in Python An Introduction.
Getting Started with Python: Constructs and Pitfalls Sean Deitz Advanced Programming Seminar September 13, 2013.
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 Functions.
Introducing Python CS 4320, SPRING Lexical Structure Two aspects of Python syntax may be challenging to Java programmers Indenting ◦Indenting is.
An Introduction. What is Python? Interpreted language Created by Guido Van Rossum – early 90s Named after Monty Python
Python Primer 1: Types and Operators © 2013 Goodrich, Tamassia, Goldwasser1Python Primer.
CS105 Computer Programming PYTHON (based on CS 11 Python track: lecture 1, CALTECH)
By Austin Laudenslager AN INTRODUCTION TO PYTHON.
Ch 1. A Python Q&A Session. Why do people use Python? Software Quality Developer productivity Program portability Support Libraries Component integration.
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!.
CSE 130 : Winter 2009 Programming Languages Lecture 11: What’s in a Name ?
1 Introduction to Object Oriented Programming Chapter 10.
Introduction to Programming Oliver Hawkins. BACKGROUND TO PROGRAMMING LANGUAGES Introduction to Programming.
Quiz 3 Topics Functions – using and writing. Lists: –operators used with lists. –keywords used with lists. –BIF’s used with lists. –list methods. Loops.
Java Programming Fifth Edition Chapter 1 Creating Your First Java Classes.
PYTHON PROGRAMMING. WHAT IS PYTHON?  Python is a high-level language.  Interpreted  Object oriented (use of classes and objects)  Standard library.
FILES AND EXCEPTIONS Topics Introduction to File Input and Output Using Loops to Process Files Processing Records Exceptions.
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.
Fundamentals of Programming I Overview of Programming
Introduction to GIS PythonScript CGIS-NURIntroduction to ArcGIS II.
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 Python is an interpreted, object-oriented and high-level programming language, which is different from a compiled one like C/C++/Java. Its.
Statement atoms The 'atomic' components of a statement are: delimiters (indents, semicolons, etc.); keywords (built into the language); identifiers (names.
Python is a general-purpose interpreted, interactive, object-oriented, and high-level programming language. It was created by Guido van Rossum during.
Introduction to Python
Introduction to Python
PHP.
Python Tutorial for C Programmer Boontee Kruatrachue Kritawan Siriboon
Python Primer 1: Types and Operators
12th Computer Science – Unit 5
Python Basics. Topics Features How does Python work Basic Features I/O in Python Operators Control Statements Function/Scope of variables OOP Concepts.
PYTHON - VARIABLES AND OPERATORS
Presentation transcript:

Introduction to Python Programming Languages Fall 2002 Adapted from Tutorial by Mark Hammond Skippi-Net, Melbourne, Australia mond

What Is Python? Created in 1990 by Guido van Rossum Created in 1990 by Guido van Rossum While at CWI, Amsterdam While at CWI, Amsterdam Now hosted by centre for national research initiatives, Reston, VA, USA Now hosted by centre for national research initiatives, Reston, VA, USA Free, open source Free, open source And with an amazing community And with an amazing community Object oriented language Object oriented language “Everything is an object” “Everything is an object”

Why Python? Designed to be easy to learn and master Designed to be easy to learn and master Clean, clear syntax Clean, clear syntax Very few keywords Very few keywords Highly portable Highly portable Runs almost anywhere - high end servers and workstations, down to windows CE Runs almost anywhere - high end servers and workstations, down to windows CE Uses machine independent byte-codes Uses machine independent byte-codes Extensible Extensible Designed to be extensible using C/C++, allowing access to many external libraries Designed to be extensible using C/C++, allowing access to many external libraries

Most obvious and notorious features Clean syntax plus high-level data types Clean syntax plus high-level data types Leads to fast coding Leads to fast coding Uses white-space to delimit blocks Uses white-space to delimit blocks Humans generally do, so why not the language? Humans generally do, so why not the language? Try it, you will end up liking it Try it, you will end up liking it Variables do not need declaration Variables do not need declaration Although not a type-less language Although not a type-less language

Pythonwin We are using Pythonwin We are using Pythonwin Only available on Windows Only available on Windows GUI toolkit using Tkinter available for most platforms GUI toolkit using Tkinter available for most platforms Standard console Python available on all platforms Standard console Python available on all platforms Has interactive mode for quick testing of code Has interactive mode for quick testing of code Includes debugger and Python editor Includes debugger and Python editor

Interactive Python Starting Python.exe, or any of the GUI environments present an interactive mode Starting Python.exe, or any of the GUI environments present an interactive mode >>> prompt indicates start of a statement or expression >>> prompt indicates start of a statement or expression If incomplete,... prompt indicates second and subsequent lines If incomplete,... prompt indicates second and subsequent lines All expression results printed back to interactive console All expression results printed back to interactive console

Variables and Types (1 of 3) Variables need no declaration Variables need no declaration >>> a=1 >>> >>> a=1 >>> As a variable assignment is a statement, there is no printed result As a variable assignment is a statement, there is no printed result >>> a 1 >>> a 1 Variable name alone is an expression, so the result is printed Variable name alone is an expression, so the result is printed

Variables and Types (2 of 3) Variables must be created before they can be used Variables must be created before they can be used >>> b Traceback (innermost last): File " ", line 1, in ? NameError: b >>> >>> b Traceback (innermost last): File " ", line 1, in ? NameError: b >>> Python uses exceptions - more detail later Python uses exceptions - more detail later

Variables and Types (3 of 3) Objects always have a type Objects always have a type >>> a = 1 >>> type(a) >>> a = "Hello" >>> type(a) >>> type(1.0) >>> a = 1 >>> type(a) >>> a = "Hello" >>> type(a) >>> type(1.0)

Assignment versus Equality Testing Assignment performed with single = Assignment performed with single = Equality testing done with double = (==) Equality testing done with double = (==) Sensible type promotions are defined Sensible type promotions are defined Identity tested with is operator. Identity tested with is operator. >>> 1==1 1 >>> 1.0==1 1 >>> "1"==1 0 >>> 1==1 1 >>> 1.0==1 1 >>> "1"==1 0

Simple Data Types Strings Strings May hold any data, including embedded NULLs May hold any data, including embedded NULLs Declared using either single, double, or triple quotes Declared using either single, double, or triple quotes >>> s = "Hi there" >>> s 'Hi there' >>> s = "Embedded 'quote'" >>> s "Embedded 'quote'" >>> s = "Hi there" >>> s 'Hi there' >>> s = "Embedded 'quote'" >>> s "Embedded 'quote'"

Simple Data Types Triple quotes useful for multi-line strings Triple quotes useful for multi-line strings >>> s = """ a long... string with "quotes" or anything else""" >>> s ' a long\012string with "quotes" or anything else' >>> len(s) 45 >>> s = """ a long... string with "quotes" or anything else""" >>> s ' a long\012string with "quotes" or anything else' >>> len(s) 45

Simple Data Types Integer objects implemented using C longs Integer objects implemented using C longs Like C, integer division returns the floor Like C, integer division returns the floor >>> 5/2 2 >>> 5/2 2 Float types implemented using C doubles Float types implemented using C doubles No point in having single precision since execution overhead is large anyway No point in having single precision since execution overhead is large anyway

Simple Data Types Long Integers have unlimited size Long Integers have unlimited size Limited only by available memory Limited only by available memory >>> long = 1L >> long ** L >>> long = 1L >> long ** L

High Level Data Types Lists hold a sequence of items Lists hold a sequence of items May hold any object May hold any object Declared using square brackets Declared using square brackets >>> l = []# An empty list >>> l.append(1) >>> l.append("Hi there") >>> len(l) 2 >>> l = []# An empty list >>> l.append(1) >>> l.append("Hi there") >>> len(l) 2

High Level Data Types >>> l [1, 'Hi there'] >>> >>> l = ["Hi there", 1, 2] >>> l ['Hi there', 1, 2] >>> l.sort() >>> l [1, 2, 'Hi there'] >>> l [1, 'Hi there'] >>> >>> l = ["Hi there", 1, 2] >>> l ['Hi there', 1, 2] >>> l.sort() >>> l [1, 2, 'Hi there']

High Level Data Types Tuples are similar to lists Tuples are similar to lists Sequence of items Sequence of items Key difference is they are immutable Key difference is they are immutable Often used in place of simple structures Often used in place of simple structures Automatic unpacking Automatic unpacking >>> point = 2,3 >>> x, y = point >>> x 2 >>> point = 2,3 >>> x, y = point >>> x 2

High Level Data Types Tuples are particularly useful to return multiple values from a function Tuples are particularly useful to return multiple values from a function >>> x, y = GetPoint() >>> x, y = GetPoint() As Python has no concept of byref parameters, this technique is used widely As Python has no concept of byref parameters, this technique is used widely

High Level Data Types Dictionaries hold key-value pairs Dictionaries hold key-value pairs Often called maps or hashes. Implemented using hash-tables Often called maps or hashes. Implemented using hash-tables Keys may be any immutable object, values may be any object Keys may be any immutable object, values may be any object Declared using braces Declared using braces >>> d={} >>> d[0] = "Hi there" >>> d["foo"] = 1 >>> d={} >>> d[0] = "Hi there" >>> d["foo"] = 1

High Level Data Types Dictionaries (cont.) Dictionaries (cont.) >>> len(d) 2 >>> d[0] 'Hi there' >>> d = {0 : "Hi there", 1 : "Hello"} >>> len(d) 2 >>> len(d) 2 >>> d[0] 'Hi there' >>> d = {0 : "Hi there", 1 : "Hello"} >>> len(d) 2

Blocks Blocks are delimited by indentation Blocks are delimited by indentation Colon used to start a block Colon used to start a block Tabs or spaces may be used Tabs or spaces may be used Maxing tabs and spaces works, but is discouraged Maxing tabs and spaces works, but is discouraged >>> if 1:... print "True"... True >>> >>> if 1:... print "True"... True >>>

Blocks Many hate this when they first see it Many hate this when they first see it Most Python programmers come to love it Most Python programmers come to love it Humans use indentation when reading code to determine block structure Humans use indentation when reading code to determine block structure Ever been bitten by the C code?: Ever been bitten by the C code?: if (1) printf("True"); CallSomething(); if (1) printf("True"); CallSomething();

Looping The for statement loops over sequences The for statement loops over sequences >>> for ch in "Hello":... print ch... H e l l o >>> >>> for ch in "Hello":... print ch... H e l l o >>>

Looping Built-in function range() used to build sequences of integers Built-in function range() used to build sequences of integers >>> for i in range(3):... print i >>> >>> for i in range(3):... print i >>>

Looping while statement for more traditional loops while statement for more traditional loops >>> i = 0 >>> while i >> >>> i = 0 >>> while i >>

Functions Functions are defined with the def statement: Functions are defined with the def statement: >>> def foo(bar):... return bar >>> >>> def foo(bar):... return bar >>> This defines a trivial function named foo that takes a single parameter bar This defines a trivial function named foo that takes a single parameter bar

Functions A function definition simply places a function object in the namespace A function definition simply places a function object in the namespace >>> foo >>> >>> foo >>> And the function object can obviously be called: And the function object can obviously be called: >>> foo(3) 3 >>> >>> foo(3) 3 >>>

Classes Classes are defined using the class statement Classes are defined using the class statement >>> class Foo:... def __init__(self):... self.member = 1... def GetMember(self):... return self.member... >>> >>> class Foo:... def __init__(self):... self.member = 1... def GetMember(self):... return self.member... >>>

Classes A few things are worth pointing out in the previous example: A few things are worth pointing out in the previous example: The constructor has a special name __init__, while a destructor (not shown) uses __del__ The constructor has a special name __init__, while a destructor (not shown) uses __del__ The self parameter is the instance (ie, the this in C++). In Python, the self parameter is explicit (c.f. C++, where it is implicit) The self parameter is the instance (ie, the this in C++). In Python, the self parameter is explicit (c.f. C++, where it is implicit) The name self is not required - simply a convention The name self is not required - simply a convention

Classes Like functions, a class statement simply adds a class object to the namespace Like functions, a class statement simply adds a class object to the namespace >>> Foo >>> >>> Foo >>> Classes are instantiated using call syntax Classes are instantiated using call syntax >>> f=Foo() >>> f.GetMember() 1 >>> f=Foo() >>> f.GetMember() 1

Modules Most of Python’s power comes from modules Most of Python’s power comes from modules Modules can be implemented either in Python, or in C/C++ Modules can be implemented either in Python, or in C/C++ import statement makes a module available import statement makes a module available >>> import string >>> string.join( ["Hi", "there"] ) 'Hi there' >>> >>> import string >>> string.join( ["Hi", "there"] ) 'Hi there' >>>

Exceptions Python uses exceptions for errors Python uses exceptions for errors try / except block can handle exceptions try / except block can handle exceptions >>> try:... 1/0... except ZeroDivisionError:... print "Eeek"... Eeek >>> >>> try:... 1/0... except ZeroDivisionError:... print "Eeek"... Eeek >>>

Exceptions try / finally block can guarantee execute of code even in the face of exceptions try / finally block can guarantee execute of code even in the face of exceptions >>> try:... 1/0... finally:... print "Doing this anyway"... Doing this anyway Traceback (innermost last): File " ", line 2, in ? ZeroDivisionError: integer division or modulo >>> >>> try:... 1/0... finally:... print "Doing this anyway"... Doing this anyway Traceback (innermost last): File " ", line 2, in ? ZeroDivisionError: integer division or modulo >>>

Threads Number of ways to implement threads Number of ways to implement threads Highest level interface modelled after Java Highest level interface modelled after Java >>> class DemoThread(threading.Thread):... def run(self):... for i in range(3):... time.sleep(3)... print i... >>> t = DemoThread() >>> t.start() >>> t.join() 0 1 >>> class DemoThread(threading.Thread):... def run(self):... for i in range(3):... time.sleep(3)... print i... >>> t = DemoThread() >>> t.start() >>> t.join() 0 1

Standard Library Python comes standard with a set of modules, known as the “standard library” Python comes standard with a set of modules, known as the “standard library” Incredibly rich and diverse functionality available from the standard library Incredibly rich and diverse functionality available from the standard library All common internet protocols, sockets, CGI, OS services, GUI services (via Tcl/Tk), database, Berkeley style databases, calendar, Python parser, file globbing/searching, debugger, profiler, threading and synchronisation, persistency, etc All common internet protocols, sockets, CGI, OS services, GUI services (via Tcl/Tk), database, Berkeley style databases, calendar, Python parser, file globbing/searching, debugger, profiler, threading and synchronisation, persistency, etc

External library Many modules are available externally covering almost every piece of functionality you could ever desire Many modules are available externally covering almost every piece of functionality you could ever desire Imaging, numerical analysis, OS specific functionality, SQL databases, Fortran interfaces, XML, Corba, COM, Win32 API, etc Imaging, numerical analysis, OS specific functionality, SQL databases, Fortran interfaces, XML, Corba, COM, Win32 API, etc Way too many to give the list any justice Way too many to give the list any justice

Python Programs Python programs and modules are written as text files with traditionally a.py extension Python programs and modules are written as text files with traditionally a.py extension Each Python module has its own discrete namespace Each Python module has its own discrete namespace Name space within a Python module is a global one. Name space within a Python module is a global one.

Python Programs Python modules and programs are differentiated only by the way they are called Python modules and programs are differentiated only by the way they are called.py files executed directly are programs (often referred to as scripts).py files executed directly are programs (often referred to as scripts).py files referenced via the import statement are modules.py files referenced via the import statement are modules

Python Programs Thus, the same.py file can be a program/script, or a module Thus, the same.py file can be a program/script, or a module This feature is often used to provide regression tests for modules This feature is often used to provide regression tests for modules When module is executed as a program, the regression test is executed When module is executed as a program, the regression test is executed When module is imported, test functionality is not executed When module is imported, test functionality is not executed

More Information on Python Can’t do Python justice in this short time frame Can’t do Python justice in this short time frame But hopefully have given you a taste of the language But hopefully have given you a taste of the language Comes with extensive documentation, including tutorials and library reference Comes with extensive documentation, including tutorials and library reference Also a number of Python books available Also a number of Python books available Visit for more details Visit for more details Can find python tutorial and reference manual Can find python tutorial and reference manual

Scripting Languages What are they? What are they? Beats me Beats me Apparently they are programming languages used for building the equivalent of shell scripts, i.e. doing the sort of things that shell scripts have traditionally been used for. Apparently they are programming languages used for building the equivalent of shell scripts, i.e. doing the sort of things that shell scripts have traditionally been used for. But any language can be used this way But any language can be used this way So it is a matter of convenience So it is a matter of convenience

Characteristics of Scripting Languages Typically intepretive Typically intepretive But that’s an implementation detail But that’s an implementation detail Typically have high level data structures Typically have high level data structures But rich libraries can substitute for this But rich libraries can substitute for this For example, look at GNAT.Spitbol For example, look at GNAT.Spitbol Powerful flexible string handling Powerful flexible string handling Typically have rich libraries Typically have rich libraries But any language can meet this requirement But any language can meet this requirement

Is Python A Scripting Language? Usually thought of as one Usually thought of as one But this is mainly a marketing issue But this is mainly a marketing issue People think of scripting languages as being easy to learn, and useful. People think of scripting languages as being easy to learn, and useful. But Python is a well worked out coherent dynamic programming language But Python is a well worked out coherent dynamic programming language And there is no reason not to use it for a wide range of applications. And there is no reason not to use it for a wide range of applications.