Programs
are composed ofmodules
,Modules
containstatements
,Statements
containexpressions
,Expressions
create and processobjects
.
def add(a, b):
return a + b
print add(3, 5) # 8
Lambdas are anonymous functions. Helpful for functional programming like map
, reduce
, etc.
def timesThree(a):
return a * 3
ints = [1, 2, 3, 4, 5]
mults = map(timesThree, ints) # [3, 6, 9, 12, 15]
mults = map(lambda a: 3 * a, ints) # [3, 6, 9, 12, 15]
# MyFile.py
title = "Meaning of Life"
% python
>>> import MyFile
>>> print MyFile.title # "Meaning of Life"
A module groups a set of functions
and classes
. Any Python source file is a module
when loaded with import
.
# Above `Account` class has been put into `account.py`
import account
checking = account.Account("Bob, 1234.56)
# another way
from account import Account
checking = Account("Bill", 4321.32)
A package is a collection of modules
and subpackages
. Any directory with Python source files, and an __init__.py
file, is a package
.
Sub-packages are just sub-directories with their own __init__.py
files.
# Above `Account` class has been put into `./bspell/` directory, and file `__init__.py` has been created
from bspell import account
checking = account.Account("Bob, 1234.56)
# another way
from bspell.account import Account
checking = Account("Bill", 4321.32)
Everything in Python is an object (class instance), and has:
identity
type
value
New types of objects can be created with class
. Classes have:
variables
methods
Constructor methods are named __init__
.
class Account:
"A simple class"
kind = "Checking"
def __init__(self, name, balance):
self.name = name
self.balance = balance
account = Account("Bob", 1234.56)
Object Type | Example creation and/or literals |
---|---|
Numbers | 1234, 3.1415 |
Strings | 'hello', "Hey" |
Lists | [1, 2, 3] |
Dictionaries | {'name': 'Brev'} |
Tuples | (1,'spam', 4,'you') |
Files | myfile = open('filename.txt', 'r') |
Other | Sets, types, None , Booleans |
- Python
strings
are immutable and cannot be changed. - Single and Double quotes are the same.
- Raw string format:
r'backslash-no-work'
- Unicode string format:
u'Иyet my friend'
- String objects do not contain pattern matching functionality!
phrase = 'Hello'
print len(phrase) # 5
print phrase[0] # first item 'H'
print phrase[-1] # last item 'o'
print phrase[-2] # second to last item 'l'
print phrase[1:3] # slice 'ell'
print 'Hell' + 'o!' # concatenate 'Hello!'
print 'Hey' * 3 # repeat 3 times 'HeyHeyHey'
print "Balance is $%.2f" % account.getBalance() # sprintf style
print dir(phrase) # List all string object methods available
String encoding methods:
S = 'X\nY\tZ'
len(S) # 5
ord('\n') # ASCII value 10
Multiple string literal via triple quote (aka HEREDOC):
msg = """
xxxxx
yyy'yy""y
zzz"""
- Lists are mutable and can be modified in-place
import re
match = re.match('Hello(.*)World(.*)', 'Hello Wide World Web')
match.group(1) # ' Wide '
match.groups() # (' Wide ', ' Web ')