Learn Python in Three Hours
Learn Python in Three Hours
in three hours
Some material adapted
from Upenn cmpe391
slides and other sources
Overview
History
Installing & Running Python
Names & Assignment
Sequences types: Lists, Tuples, and
Strings
Mutability
Python is an experiment in
how much freedom programmers need. Too much freedom
and nobody can read another's
code; too little and expressiveness is endangered.
- Guido van Rossum
http://docs.python.org/
Running
Python
Installing
Python is pre-installed on most Unix systems,
including Linux and MAC OS X
The pre-installed version may not be the most
recent one (2.6.2 and 3.1.1 as of Sept 09)
Download from http://python.org/download/
Python comes with a large library of standard
modules
There are several options for an IDE
IDLE works well with Windows
Emacs with python-mode or your favorite text editor
Eclipse with Pydev (http://pydev.sourceforge.net/)
if x == 0:
return 1
return x * fact(x - 1)
print
print N fact(N)
print "---------"
for n in range(10):
print n, fact(n)
Python Scripts
When you call a python program from the
command line the interpreter evaluates each
expression in the file
Familiar mechanisms are used to provide
command line arguments and/or redirect
input and output
Python also has mechanisms to allow a
python program to act both as a script and as
a module to be imported and used by another
python program
Example of a Script
#! /usr/bin/python
""" reads text from standard input and outputs any email
addresses it finds, one to a line.
"""
import re
from sys import stdin
# a regular expression ~ for a valid email address
pat = re.compile(r'[-\w][-.\w]*@[-\w][-\w.]+[a-zA-Z]{2,4}')
for line in stdin.readlines():
for address in pat.findall(line):
print address
results
python> python email0.py <email.txt
[email protected]
[email protected]
[email protected]
[email protected]
python>
found = set( )
for line in stdin.readlines():
for address in pat.findall(line):
found.add(address)
results
python> python email2.py <email.txt
[email protected]
[email protected]
[email protected]
python>
deffact1(n):
ans=1
foriinrange(2,n):
ans=ans*n
returnans
deffact2(n):
ifn<1:
return1
else:
returnn*fact2(n1)
The Basics
Basic Datatypes
Integers (default for numbers)
z = 5 / 2 # Answer 2, integer division
Floats
x = 3.456
Strings
Can use or to specify with abc == abc
Unmatched can occur within the string:
matts
Use triple double-quotes for multi-line strings or
strings than contain both and inside of them:
abc
Whitespace
Whitespace is meaningful in Python: especially
indentation and placement of newlines
Use a newline to end a line of code
Use \ when must go to next line prematurely
Comments
Start comments with #, rest of line is ignored
Can include a documentation string as the
first line of a new function or class you define
Development environments, debugger, and
other tools use it: its good style to include one
def fact(n):
fact(n) assumes n is a positive
integer and returns facorial of n.
assert(n>0)
return 1 if n==1 else n*fact(n-1)
Assignment
Binding a variable in Python means setting a name to
hold a reference to some object
Assignment creates references, not copies
Naming Rules
Names are case sensitive and cannot start
with a number. They can contain letters,
numbers, and underscores.
bob
Bob
_bob
_2_bob_
bob_2
BoB
Naming conventions
The Python community has these recommended naming conventions
joined_lower for functions, methods and,
attributes
joined_lower or ALL_CAPS for constants
StudlyCaps for classes
camelCase only to conform to pre-existing
conventions
Attributes: interface, _internal, __private
Assignment
You can assign to multiple names at the
same time
>>> x, y = 2, 3
>>> x
2
>>> y
3
Sequence types:
Tuples, Lists, and
Strings
Sequence Types
1. Tuple: (john, 32, [CMSC])
A simple immutable ordered sequence of
items
Items can be of mixed types, including
collection types
Similar Syntax
All three sequence types (tuples,
strings, and lists) share much of the
same syntax and functionality.
Key difference:
Tuples and strings are immutable
Lists are mutable
The operations shown in this section
can be applied to all sequence types
most examples will just show the
operation performed on one
Sequence Types 1
Define tuples using parentheses and commas
>>> tu = (23, abc, 4.56, (2,3), def)
= Hello World
= Hello World
= This is a multi-line
that uses triple quotes.
Sequence Types 2
Access individual members of a tuple, list, or
string using square bracket array notation
Note that all are 0 based
>>> tu = (23, abc, 4.56, (2,3), def)
>>> tu[1]
# Second item in the tuple.
abc
>>> li = [abc, 34, 4.34, 23]
>>> li[1]
# Second item in the list.
34
>>> st = Hello World
>>> st[1]
# Second character in string.
e
The in Operator
Boolean test whether a value is inside a container:
>>> t
>>> 3
False
>>> 4
True
>>> 4
False
= [1, 2, 4, 5]
in t
in t
not in t
The + Operator
The + operator produces a new tuple, list, or
string whose value is the concatenation of its
arguments.
>>> (1, 2, 3) + (4, 5, 6)
(1, 2, 3, 4, 5, 6)
>>> [1, 2, 3] + [4, 5, 6]
[1, 2, 3, 4, 5, 6]
>>> Hello + + World
Hello World
The * Operator
The * operator produces a new tuple, list, or
string that repeats the original content.
>>> (1, 2, 3) * 3
(1, 2, 3, 1, 2, 3, 1, 2, 3)
>>> [1, 2, 3] * 3
[1, 2, 3, 1, 2, 3, 1, 2, 3]
>>> Hello * 3
HelloHelloHello
Mutability:
Tuples vs. Lists
Potentially confusing:
extend takes a list as an argument.
append takes a singleton as an argument.
>>> li.append([10, 11, 12])
>>> li
[1, 2, i, 3, 4, 5, a, 9, 8, 7, [10,
11, 12]]
>>> li.sort()
>>> li
[2, 5, 6, 8]
>>> li.sort(some_function)
# sort in place using user-defined comparison
Tuple details
The comma is the tuple creation operator, not parens
>>> 1,
(1,)