Python was created in 1990 by Guido van Rossum as a hobby project. It is a highly portable, interpreted programming language that is designed to be easy to learn and read. Python code tends to be shorter and more readable than comparable code in other languages like C or Java due to its clear syntax and use of whitespace.
2. What Is Python?
What Is Python?
Created in 1990 by Guido van Rossum
Created in 1990 by Guido van Rossum
About the origin of Python, Van Rossum wrote in 1996:
About the origin of Python, Van Rossum wrote in 1996:
Over six years ago, in December 1989, I was looking for a
Over six years ago, in December 1989, I was looking for a
"hobby" programming project that would keep me occupied
"hobby" programming project that would keep me occupied
during the week around Christmas. My office … would be
during the week around Christmas. My office … would be
closed, but I had a home computer, and not much else on my
closed, but I had a home computer, and not much else on my
hands. I decided to write an interpreter for the new scripting
hands. I decided to write an interpreter for the new scripting
language I had been thinking about lately: a descendant of
language I had been thinking about lately: a descendant of
ABC that would appeal to Unix/C hackers. I chose Python as a
ABC that would appeal to Unix/C hackers. I chose Python as a
working title for the project, being in a slightly irreverent
working title for the project, being in a slightly irreverent
mood (and a big fan of Monty Python's Flying Circus).
mood (and a big fan of Monty Python's Flying Circus).
3. Is Python A Scripting Language?
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
People think of scripting languages as being
easy to learn, and useful.
easy to learn, and useful.
But Python is a well worked out coherent
But Python is a well worked out coherent
dynamic programming language
dynamic programming language
And there is no reason not to use it for a wide
And there is no reason not to use it for a wide
range of applications.
range of applications.
4. Design Philosophy
Design Philosophy
>>> import this
>>> import this
The Zen of Python, by Tim Peters
The Zen of Python, by Tim Peters
Beautiful is better than ugly.
Beautiful is better than ugly.
Explicit is better than implicit.
Explicit is better than implicit.
Simple is better than complex.
Simple is better than complex.
Complex is better than complicated.
Complex is better than complicated.
Flat is better than nested.
Flat is better than nested.
Sparse is better than dense.
Sparse is better than dense.
Readability counts.
Readability counts.
Special cases aren't special enough to break the rules.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Although practicality beats purity.
Errors should never pass silently.
Errors should never pass silently.
Unless explicitly silenced.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Now is better than never.
Although never is often better than *right* now.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Namespaces are one honking great idea -- let's do more of those!
5. Why Python?
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
Runs almost anywhere - high end servers and
workstations, down to windows CE
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
Designed to be extensible using C/C++, allowing
access to many external libraries
access to many external libraries
6. Most obvious and notorious
Most obvious and notorious
features
features
Clean syntax plus high-level data types
Clean syntax plus high-level data types
Leads to fast coding (First language in many
Leads to fast coding (First language in many
universities abroad!)
universities abroad!)
Uses white-space to delimit blocks
Uses white-space to delimit blocks
Humans generally do, so why not the
Humans generally do, so why not the
language?
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
7. Productivity!
Productivity!
Reduced development time
Reduced development time
code is 2-10x shorter than C, C++, Java
code is 2-10x shorter than C, C++, Java
Improved program maintenance
Improved program maintenance
code is extremely readable
code is extremely readable
Less training
Less training
language is very easy to learn
language is very easy to learn
8. What is it used for?
What is it used for?
rapid prototyping
rapid prototyping
web scripting
web scripting
throw-away, ad hoc programming
throw-away, ad hoc programming
steering scientific applications
steering scientific applications
extension language
extension language
XML processing
XML processing
database applications
database applications
GUI applications
GUI applications
A Glue Language
A Glue Language
10. Python vs. Perl
Python vs. Perl
Easier to learn
Easier to learn
important for occasional users
important for occasional users
More readable code
More readable code
improved code maintenance
improved code maintenance
Fewer “magical” side effects
Fewer “magical” side effects
More “safety” guarantees
More “safety” guarantees
Better Java integration
Better Java integration
Less Unix bias
Less Unix bias
11. Python vs. Tcl
Python vs. Tcl
Real datatypes, object-orientation
Real datatypes, object-orientation
More differentiated syntax
More differentiated syntax
Much faster (even than Tcl 8.x)
Much faster (even than Tcl 8.x)
Less need for C extensions
Less need for C extensions
C extensions don’t redefine syntax
C extensions don’t redefine syntax
hence fewer extension conflicts
hence fewer extension conflicts
Better Java integration
Better Java integration
Python uses Tk as de-facto GUI std
Python uses Tk as de-facto GUI std
12. Python vs. Java
Python vs. Java
Code 5-10 times more concise
Code 5-10 times more concise
Dynamic typing
Dynamic typing
Much quicker development
Much quicker development
no compilation phase
no compilation phase
less typing
less typing
Yes, it runs slower
Yes, it runs slower
but development is so much faster!
but development is so much faster!
Use Python with Java: Jython!
Use Python with Java: Jython!
14. Python Programs
Python Programs
Python programs and modules are written
Python programs and modules are written
as text files with traditionally a
as text files with traditionally a .py
.py
extension
extension
Each Python module has its own discrete
Each Python module has its own discrete
namespace
namespace
Name space within a Python module is a
Name space within a Python module is a
global one.
global one.
15. Python Programs
Python Programs
Python modules and programs are
Python modules and programs are
differentiated only by the way they are
differentiated only by the way they are
called
called
.py files executed directly are programs (often
.py files executed directly are programs (often
referred to as scripts)
referred to as scripts)
.py files referenced via the
.py files referenced via the import
import statement
statement
are modules
are modules
16. Python Programs
Python Programs
Thus, the same .py file can be a
Thus, the same .py file can be a
program/script, or a module
program/script, or a module
This feature is often used to provide
This feature is often used to provide
regression tests for modules
regression tests for modules
When module is executed as a program, the
When module is executed as a program, the
regression test is executed
regression test is executed
When module is imported, test functionality is
When module is imported, test functionality is
not executed
not executed
17. Variables and Types
Variables and Types (1 of 3)
(1 of 3)
Variables need no declaration
Variables need no declaration
>>> a=1
>>> a=1
>>>
>>>
As a variable assignment is a statement,
As a variable assignment is a statement,
there is no printed result
there is no printed result
>>> a
>>> a
1
1
Variable name alone is an expression, so
Variable name alone is an expression, so
the result is printed
the result is printed
18. Variables and Types
Variables and Types (2 of 3)
(2 of 3)
Variables must be created before they can
Variables must be created before they can
be used
be used
>>> b
>>> b
Traceback (innermost last):
Traceback (innermost last):
File "<interactive input>", line
File "<interactive input>", line
1, in ?
1, in ?
NameError: b
NameError: b
>>>
>>>
Python uses exceptions - more detail later
Python uses exceptions - more detail later
19. Variables and Types
Variables and Types (3 of 3)
(3 of 3)
Objects always have a type
Objects always have a type
>>> a = 1
>>> a = 1
>>> type(a)
>>> type(a)
<type 'int'>
<type 'int'>
>>> a = "Hello"
>>> a = "Hello"
>>> type(a)
>>> type(a)
<type 'string'>
<type 'string'>
>>> type(1.0)
>>> type(1.0)
<type 'float'>
<type 'float'>
20. Assignment versus Equality
Assignment versus Equality
Testing
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
Identity tested with is
is operator.
operator.
>>> 1==1
>>> 1==1
1
1
>>> 1.0==1
>>> 1.0==1
1
1
>>> "1"==1
>>> "1"==1
0
0
21. Simple Data Types
Simple Data Types
Strings
Strings
May hold any data, including embedded
May hold any data, including embedded
NULLs
NULLs
Declared using either single, double, or triple
Declared using either single, double, or triple
quotes
quotes
>>> s = "Hi there"
>>> s = "Hi there"
>>> s
>>> s
'Hi there'
'Hi there'
>>> s = "Embedded 'quote'"
>>> s = "Embedded 'quote'"
>>> s
>>> s
"Embedded 'quote'"
"Embedded 'quote'"
22. Simple Data Types
Simple Data Types
Triple quotes useful for multi-line strings
Triple quotes useful for multi-line strings
>>> s = """ a long
>>> s = """ a long
... string with "quotes" or
... string with "quotes" or
anything else"""
anything else"""
>>> s
>>> s
' a long012string with "quotes" or
' a long012string with "quotes" or
anything else'
anything else'
>>> len(s)
>>> len(s)
45
45
23. Simple Data Types
Simple Data Types
Integer objects implemented using C
Integer objects implemented using C
longs
longs
Like C, integer division returns the floor
Like C, integer division returns the floor
>>> 5/2
>>> 5/2
2
2
Float types implemented using C doubles
Float types implemented using C doubles
No point in having single precision since
No point in having single precision since
execution overhead is large anyway
execution overhead is large anyway
24. Simple Data Types
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 << 64
>>> long = 1L << 64
>>> long ** 5
>>> long ** 5
21359870359209100823950217061695521146027045223
21359870359209100823950217061695521146027045223
56652769947041607822219725780640550022962086936
56652769947041607822219725780640550022962086936
576L
576L
25. High Level Data Types
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 = []# An empty list
>>> l.append(1)
>>> l.append(1)
>>> l.append("Hi there")
>>> l.append("Hi there")
>>> len(l)
>>> len(l)
2
2
26. High Level Data Types
High Level Data Types
>>> l
>>> l
[1, 'Hi there']
[1, 'Hi there']
>>>
>>>
>>> l = ["Hi there", 1, 2]
>>> l = ["Hi there", 1, 2]
>>> l
>>> l
['Hi there', 1, 2]
['Hi there', 1, 2]
>>> l.sort()
>>> l.sort()
>>> l
>>> l
[1, 2, 'Hi there']
[1, 2, 'Hi there']
27. High Level Data Types
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
>>> point = 2,3
>>> x, y = point
>>> x, y = point
>>> x
>>> x
2
2
28. High Level Data Types
High Level Data Types
Tuples are particularly useful to return
Tuples are particularly useful to return
multiple values from a function
multiple values from a function
>>> x, y = GetPoint()
>>> x, y = GetPoint()
As Python has no concept of byref
As Python has no concept of byref
parameters, this technique is used widely
parameters, this technique is used widely
29. High Level Data Types
High Level Data Types
Dictionaries hold key-value pairs
Dictionaries hold key-value pairs
Often called maps or hashes. Implemented
Often called maps or hashes. Implemented
using hash-tables
using hash-tables
Keys may be any immutable object, values
Keys may be any immutable object, values
may be any object
may be any object
Declared using braces
Declared using braces
>>> d={}
>>> d={}
>>> d[0] = "Hi there"
>>> d[0] = "Hi there"
>>> d["foo"] = 1
>>> d["foo"] = 1
30. High Level Data Types
High Level Data Types
Dictionaries (cont.)
Dictionaries (cont.)
>>> len(d)
>>> len(d)
2
2
>>> d[0]
>>> d[0]
'Hi there'
'Hi there'
>>> d = {0 : "Hi there", 1 :
>>> d = {0 : "Hi there", 1 :
"Hello"}
"Hello"}
>>> len(d)
>>> len(d)
2
2
31. Blocks
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
Maxing tabs and spaces works, but is
discouraged
discouraged
>>> if 1:
>>> if 1:
...
... print "True"
print "True"
...
...
True
True
>>>
>>>
32. Blocks
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
Humans use indentation when reading
code to determine block structure
code to determine block structure
Ever been bitten by the C code?:
Ever been bitten by the C code?:
if (1)
if (1)
printf("True");
printf("True");
CallSomething();
CallSomething();
33. Looping
Looping
The
The for
for statement loops over sequences
statement loops over sequences
>>> for ch in "Hello":
>>> for ch in "Hello":
...
... print ch
print ch
...
...
H
H
e
e
l
l
l
l
o
o
>>>
>>>
34. Looping
Looping
Built-in function
Built-in function range()
range() used to build
used to build
sequences of integers
sequences of integers
>>> for i in range(3):
>>> for i in range(3):
... print i
... print i
...
...
0
0
1
1
2
2
>>>
>>>
35. Looping
Looping
while
while statement for more traditional
statement for more traditional
loops
loops
>>> i = 0
>>> i = 0
>>> while i < 2:
>>> while i < 2:
... print i
... print i
... i = i + 1
... i = i + 1
...
...
0
0
1
1
>>>
>>>
36. Functions
Functions
Functions are defined with the
Functions are defined with the def
def
statement:
statement:
>>> def foo(bar):
>>> def foo(bar):
... return bar
... return bar
>>>
>>>
This defines a trivial function named
This defines a trivial function named foo
foo
that takes a single parameter
that takes a single parameter bar
bar
37. Functions
Functions
A function definition simply places a
A function definition simply places a
function object in the namespace
function object in the namespace
>>> foo
>>> foo
<function foo at fac680>
<function foo at fac680>
>>>
>>>
And the function object can obviously be
And the function object can obviously be
called:
called:
>>> foo(3)
>>> foo(3)
3
3
>>>
>>>
38. Classes
Classes
Classes are defined using the
Classes are defined using the class
class
statement
statement
>>> class Foo:
>>> class Foo:
... def __init__(self):
... def __init__(self):
... self.member = 1
... self.member = 1
... def GetMember(self):
... def GetMember(self):
... return self.member
... return self.member
...
...
>>>
>>>
39. Classes
Classes
A few things are worth pointing out in the
A few things are worth pointing out in the
previous example:
previous example:
The constructor has a special name
The constructor has a special name
__init__
__init__, while a destructor (not shown)
, while a destructor (not shown)
uses
uses __del__
__del__
The
The self
self parameter is the instance (ie, the
parameter is the instance (ie, the
this
this in C++). In Python, the self parameter
in C++). In Python, the self parameter
is explicit (c.f. C++, where it is implicit)
is explicit (c.f. C++, where it is implicit)
The name
The name self
self is not required - simply a
is not required - simply a
convention
convention
40. Classes
Classes
Like functions, a class statement simply
Like functions, a class statement simply
adds a class object to the namespace
adds a class object to the namespace
>>> Foo
>>> Foo
<class __main__.Foo at 1000960>
<class __main__.Foo at 1000960>
>>>
>>>
Classes are instantiated using call syntax
Classes are instantiated using call syntax
>>> f=Foo()
>>> f=Foo()
>>> f.GetMember()
>>> f.GetMember()
1
1
41. Modules
Modules
Most of Python’s power comes from
Most of Python’s power comes from
modules
modules
Modules can be implemented either in
Modules can be implemented either in
Python, or in C/C++
Python, or in C/C++
import
import statement makes a module
statement makes a module
available
available
>>> import string
>>> import string
>>> string.join( ["Hi", "there"] )
>>> string.join( ["Hi", "there"] )
'Hi there'
'Hi there'
>>>
>>>
43. Exceptions
Exceptions
try
try /
/ finally
finally block can guarantee
block can guarantee
execute of code even in the face of
execute of code even in the face of
exceptions
exceptions
>>> try:
>>> try:
... 1/0
... 1/0
... finally:
... finally:
... print "Doing this anyway"
... print "Doing this anyway"
...
...
Doing this anyway
Doing this anyway
Traceback (innermost last): File "<interactive
Traceback (innermost last): File "<interactive
input>", line 2, in ?
input>", line 2, in ?
ZeroDivisionError: integer division or modulo
ZeroDivisionError: integer division or modulo
>>>
>>>
44. Threads
Threads
Number of ways to implement threads
Number of ways to implement threads
Highest level interface modelled after
Highest level interface modelled after
Java
Java
>>> class DemoThread(threading.Thread):
>>> class DemoThread(threading.Thread):
... def run(self):
... def run(self):
... for i in range(3):
... for i in range(3):
... time.sleep(3)
... time.sleep(3)
... print i
... print i
...
...
>>> t = DemoThread()
>>> t = DemoThread()
>>> t.start()
>>> t.start()
>>> t.join()
>>> t.join()
0
0
1
1 <etc>
<etc>
45. Standard Library
Standard Library
Python comes standard with a set of modules,
Python comes standard with a set of modules,
known as the “standard library”
known as the “standard library”
Incredibly rich and diverse functionality available
Incredibly rich and diverse functionality available
from the standard library
from the standard library
All common internet protocols, sockets, CGI, OS
All common internet protocols, sockets, CGI, OS
services, GUI services (via Tcl/Tk), database,
services, GUI services (via Tcl/Tk), database,
Berkeley style databases, calendar, Python
Berkeley style databases, calendar, Python
parser, file globbing/searching, debugger,
parser, file globbing/searching, debugger,
profiler, threading and synchronisation,
profiler, threading and synchronisation,
persistency, etc
persistency, etc
46. External library
External library
Many modules are available externally
Many modules are available externally
covering almost every piece of
covering almost every piece of
functionality you could ever desire
functionality you could ever desire
Imaging, numerical analysis, OS specific
Imaging, numerical analysis, OS specific
functionality, SQL databases, Fortran
functionality, SQL databases, Fortran
interfaces, XML, Corba, COM, Win32 API,
interfaces, XML, Corba, COM, Win32 API,
comedilib, serial, parallel, opengl, opencv,
comedilib, serial, parallel, opengl, opencv,
wxpython, gtk, qt, tkinter etc
wxpython, gtk, qt, tkinter etc
Way too many to give the list any justice
Way too many to give the list any justice
47. More Information on Python
More Information on Python
Comes with extensive documentation,
Comes with extensive documentation,
including tutorials and library reference
including tutorials and library reference
Also a number of Python books available
Also a number of Python books available
Visit
Visit www.python.org
www.python.org for more details
for more details
Can find python tutorial and reference manual
Can find python tutorial and reference manual