Python Crash Course 0.07 PDF
Python Crash Course 0.07 PDF
Python Crash Course 0.07 PDF
2010-01-15 v0.07
Philippe Lagadec
http://www.decalage.info
This document published on the site www.decalage.info is licensed by Philippe Lagadec under a Creative Commons
Attribution-Noncommercial-Share Alike 3.0 Unported License.
Introduction
“Python is an easy to learn, powerful
programming language. It has efficient high-
level data structures and a simple but effective
approach to object-oriented programming.
Python's elegant syntax and dynamic typing,
together with its interpreted nature, make it an
ideal language for scripting and rapid
application development in many areas on
most platforms.”
The Python Tutorial, http://docs.python.org/tutorial/
Why “Python” ?
“Guido van Rossum, the creator of the
Python language, named the language
after the BBC show "Monty Python's
Flying Circus". He doesn't particularly
like snakes that kill animals for food by
winding their long bodies around them
and crushing them.”
Swaroop C H.
Download a Python interpreter
Python official website:
http://www.python.org
Download:
http://www.python.org/download
Warning: for now (Jan 2010), Python 2.6
or 2.5 are still recommended.
Many third-party modules have issues with
Python 3.x, which is very different from v2.x.
Install a Python-aware editor
On Windows, I recommend PyScripter to
get an effective IDE with syntax
highlighting, code completion, integrated
Python shell and debugger: http://mmm-
experts.com/Products.aspx?ProductId=4
or http://code.google.com/p/pyscripter/ for
latest versions.
On other OSes such as Linux or
MacOSX, try Eclipse + PyDev.
Python Documentation
On Windows, the manual provided with the
interpreter (Start menu / All Programs / Python /
Python Manuals) is usually the most convenient
way to access the Python documentation.
Use the index tab !
Online official documentation startpoint:
http://www.python.org/doc
(pretty long) official tutorial:
http://docs.python.org/tut/tut.html
Python shell
On Windows, use Start Menu / Python / Python
command line.
Alternatively you may run "python" from a CMD
window.
but since python.exe is not in the PATH environment
variable by default you may want to add it, or type its
complete path such as "C:\python25\python.exe".
Quit with Ctrl+Z or simply close the window
when finished.
Python basics
Variables and Constants
Variables are simply names which point to any
value or object:
a_string = "hello, world"
an_integer = 12
a_float = 3.14
a_boolean = True
nothing = None
Dynamic typing: the value or type of a variable
may be changed at any time.
Print
To print a constant or variable:
print "hello, world"
print a_string
print 12
print (5+3)/2
To print several items, use commas
(items will be separated by spaces):
print "abc", 12, a_float
Long lines
A long statement may be split using a
backslash:
my_very_long_variable = something + \
something_else
string_double_quotes = "abc"
string_triple_quotes = """this is
a multiline
string."""
Strings
It's useful when we need to include
quotes in a string:
string1 = 'hello "world"'
string2 = "don't"
otherwise we have to use backslashes:
string2 = 'don\'t'
Be careful about backslashes in paths:
Win_path = 'C:\\Windows\\System32'
String operations and methods
Strings are objects which support many operations:
strings = string1 + " : " + string2
Get the length of a string:
len(strings)
Convert to uppercase:
strings_uppercase = strings.upper()
Strip spaces at beginning and end of a string:
stripped = a_string.strip()
Replace a substring inside a string:
newstring = a_string.replace('abc', 'def')
All string methods: http://docs.python.org/lib/string-methods.html
Note: a string is immutable, all operations create a new string in
memory.
Conversions
Convert a string to an integer and vice-
versa:
i = 12
s = str(i)
s = '17'
i = int(s)
Building strings
Several ways to include a variable into a string:
by concatenation:
string1 = 'the value is ' + str(an_integer) + '.'
by "printf-like" formatting:
string2 = 'the value is %d.' % an_integer
With several variables, we need to use
parentheses:
a = 17
b = 3
string3 = '%d + %d = %d' % (a, b, a+b)
Building strings
To include strings into another string:
stringa = '17'
stringb = '3'
stringc = 'a = ' + stringa + ', b = ' + stringb
stringd = 'a = %s, b= %s' % (stringa, stringb)
Everything about string formatting:
http://docs.python.org/library/stdtypes.html#strin
g-formatting-operations
Lists
A list is a dynamic array of any objects.
It is declared with square brackets:
mylist = [1, 2, 3, 'abc', 'def']
if a != 'test':
print 'a is not "test"'
test_mode = False
else:
print 'The value of a is:'
print 'a="test"'
test_mode = True
if / elif / else
if choice == 1:
print “First choice.”
elif choice == 2:
print “Second choice.”
else:
print “Wrong choice.”
While loop
a=1
while a<10:
print a
a += 1
For loop
for a in range(10):
print a
import sys
print “all arguments:”, sys.argv
print “number of args:”, len(sys.argv)
print “first arg:”, sys.argv[1]
Launching a process/command
Simplest way:
import os
os.system(“net accounts”)
More effective and flexible:
See subprocess module
• Capture output
• Control keyboard input
• Execution in parallel
Exercises
1) Write a script which computes the
SHA1 hash of your name.
root = ET.fromstring(xml_soap_message)
elem_env = root.find(ENVELOPE)
elem_body = elem_env.find(BODY)
More about ElementTree
More complete tutorials about parsing,
generating and editing XML with
ElementTree:
http://effbot.org/zone/element-index.htm
http://effbot.org/zone/element.htm
http://www.decalage.info/en/python/etree
Simple web applications
Using CherryPy
Simplest web application
import cherrypy
class HelloWorld:
def index(self):
return "Hello world!“
index.exposed = True
cherrypy.quickstart(HelloWorld())
Two pages
import cherrypy
class TwoPages:
def index(self):
return „<a href=“page2”>Go to page 2</a>‟
index.exposed = True
def page2(self):
return “This is page 2!“
page2.exposed = True
cherrypy.quickstart(TwoPages())
CherryPy tutorial
Tutorial:
http://www.cherrypy.org/wiki/CherryPyTutorial
Sample scripts
See also local samples in your Python directory,
such as:
• C:\Python25\Lib\site-packages\cherrypy\tutorial\
Documentation:
http://www.cherrypy.org/wiki/TableOfContents