Xman Blog Inside

Monday, September 11, 2006

Python Core Language Quick Reference

If you can learn a language by example, this is a place for you to learn the core of python programming. However, some statements are mis-indented. But indentation should not be a problem to you if you are familiar with structured programming.

# Getting started.
>>> print "hello world"
hello world

xman@sai python $ cat hello.py
#!/usr/bin/python
# hello world comment
print "hello world"

>>> execfile("hello.py")
hello world

>>> import sys
>>> sys.exit()
xman@sai python $

>>> while x <= y:
... print x,y
... x=x+1
>>> x = 0 ; y = 1 ; z = 2
>>> print "%4d %0.2f" % (x,y)
100 5.00

# Conditional.
>>> if x < z =" x"> y:
... z = y
... elif x == y:
... pass
... else:
... raise RuntimeError, "Unknown"
...

# Keywords: and assert break class continue def del elif else except exec finally for from global
if import in is lambda not or pass print raise return try while
# Operators: + - * ** / % << >> < > <= >= == != <> & | ^ ~ not and or

# File.
>>> f = open("hello.py")
>>> line = f.readline()
>>> while line:
... print line
... line = f.readline()
...
>>> f.close()

# File methods
f.read([n])
f.readline()
f.readlines()
f.write(s) # Write string s.
f.writelines(l) # Write all strings in list l.
f.close()
f.tell()
f.seek(offset [,where])
f.isatty()
f.flush()
f.truncate([size])
f.fileno()
f.readinto(buffer, nbytes)

# String & Char
>>> a = "hello world"
>>> print a[4]
o
>>> a = 'hello world'
>>> b = "hello world"
>>> c = """hello world"""
>>> d = """hello
... world
... """

>>> print d
hello
world

# Slice
>>> x = a[0:5]
>>> y = a[1:]
>>> z = a[:4]

# String
>>> a = "hello" ; b = "world"
>>> c = a + b ; print c
helloworld

# List
>>> data = ["a", "b", "c"]
>>> data.append("d")
>>> data = data + ['e','f']

# Reference count
>>> a = [1,3,5]
>>> b = a
>>> a, b
([1, 3, 5], [1, 3, 5])
>>> b[1] = 100
>>> a, b
([1, 100, 5], [1, 100, 5])

# Nested list.
>>> data = ['a' , ['b','c' ]]
>>> print data[1][1]
c

# Map.
>>> import string
>>> import sys
>>> f = open("data.dat")
>>> svalues = f.readlines()
>>> f.close()
>>> fvalues = map(string.atof, svalues)
>>> print svalues
['0.1\n', '0.4\n', '0.2\n', '0.3\n', '0.24\n']
>>> print fvalues
[0.10000000000000001, 0.40000000000000002, 0.20000000000000001, 0.29999999999999999, 0.2399999999
9999999]
>>> print min(fvalues)
0.1
>>> print max(fvalues)
0.4

# Tuple (Create once, no modifications allowed)
>>> a = (1,3)
>>> b = (2,4)
>>> c = (4,)
>>> print a,b,c
(1, 3) (2, 4) (4,)
>>> print a[0], a[1]

# Range.
>>> print range(3)
[0, 1, 2]
>>> print range(1,10)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> print range(1,10,2)
[1, 3, 5, 7, 9]
>>> for i in range(1,10,2):
... print i
...
1
3
5
7
9
a = xrange(0,10000000) # Recompute to save memory.

# Dictionary (associative array).
>>> a = {
... "a" : "va" ,
... "b" : "vb"
... }
>>> print a["a"], a["b"]
>>> a.keys()
>>> a.has_key("a")
>>> del a["a"]

# Function. Local scope by default.
>>> def swap(a,b,c=0):
... "SWAP: Documentation string"
... global msg
... if c != 0 : print msg
... return (b,a)
...
>>> a,b=swap(a,b)
>>> a,b=swap(a,b,1)

# Variable-length argument, keyword argument.
# args: Additional variables in a tuple.
# kw: Additional keyword arguments in a table.
>>> def func(x, *args, **kw):

# Class.
# def: Define a method.
# First argument of a method: the object.
>>> class stack:
... "Stack data structure"
... name = "Stack"
... def __init__(self):
... self.stack = []
... def push(self,object):
... "Append object to the end"
... self.stack.append(object)
... def pop(self):
... "Remove an object from the end and return it"
... return self.stack.pop()
... def length(self):
... "Number of objects in stack"
... return len(self.stack)
>>> s = stack()
>>> s.push("data1")
>>> s.push("data2")
>>> x = s.pop()

# Inheritance.
>>> class C(A,B):
# Encapsulation.
>>> class C:
... __x = 500

# Class relationship
>>> isinstance(c,C)
>>> issubclass(C,A)


# Exception.
>>> try:
... f = open("data.txt")
... except IOError, e:
... print "My error:" , e
...
My error: [Errno 2] No such file or directory: 'data.txt'

# Module.
# Import the module hello.py.
>>> import hello
>>> import string
>>> dir(string) # List contents of module string.

# Syntax.
# Multi-line.
>>> c = a + \
... b

# Consistent indentation.
# Codes in the same block must uses the same indentation.

# Documentation strings.

>>> def func(n):
... "Documentation string"
... return n

# Type & ID
>>> type(a)

>>> id(a)
5280552
>>> a is b
>>> a is not b
>>> type(a) == type(b)

# Copy.
>>> import copy
>>> b = [1,2,3]
>>> a = copy.deepcopy(b)

# List:
list(s)
s.append(x)
s.extend(x)
s.count(x)
s.index(x)
s.insert(i,x)
s.pop([i])
s.remove(x)
s.reverse()
s.sort([cmpfunc])

# Mapping types:
len(m)
m[k]
del m[k]
m.clear()
m.copy()
m.has_key(k)
m.items()
m.keys()
m.update(b)
m.values()
m.get(k,[,f]) # Return m[k] if found; otherwise return f.

# Unbound method object, bound method object.
# C is a class, c is an instance of class C.
>>> c.work()
hello world
>>> C.work(c)
hello world

# Functional programming
>>> a = lambda x,y : x+y
>>> print a(2,5)

# map(), reduce(), filter().
# Apply func to elements in s.
>>> t = map(func,s)
# Reduce a using sum function.
>>> b = reduce(sum, a)
# Filter objects which satisfy the conditions.
>>> b = filter(lambda x: x < style="font-weight: bold;"># Execution.
# eval(str, [,globals [,locals]])
>>> c = eval('a+b')
>>> exec "print 4+3"
# execfile(filename [,globals [,locals]])
>>> execfile("hello.py")
# compile(str,filename,kind)
>>> c = compile(str, '', 'single')
>>> c = compile(str, '', 'exec')
>>> c = compile(str, '', 'eval')

# Input, Output
>>> s = raw_input("type something")
>>> c = sys.stdin.read(1)
>>> sys.stdout = open("output.txt", "w")

# Serialize
>>> f = open("save.dat", "w")
>>> pickle.dump(a,f)
>>> pickle.dump(b,f)
>>> f.close()
>>> f = open("save.dat", "r")
>>> obj = pickle.load(f)
>>> obj
2

# Built-in Functions
abs(x)
apply(func [,args [,keywords]])
buffer(object [,offset [,size]])
callable(obj)
chr(i)
cmp(x,y)
coerce(x,y)
compile(string, filename, kind)
complex(real [,img])
delattr(obj, attr)
dir([obj])
divmod(a,b)
eval(expr [, globals [,locals]])
execfile(filename [,globals [,locals]])
filter(function, list)
float(x)
getattr(obj,name)
globals()
hasattr(obj,name)
hash(obj)
hex(x)
id(obj)
input([prompt])
intern(string)
isinstance(obj,class)
issubclass(subclass,class)
len(s)
list(s)
locals()
long(x)
map(function, list, ...)
max(s [,args, ...])
min(s [,args, ...])
oct(x)
open(fname [, mode [, bufsize]])
ord(c)
power(x, y, [,z])
range([start,] stop [,step])
raw_input([prompt])
reduce(func, seq [,initializer])
reload(module)
repr(obj)
round(x [,n])
setattr(obj, name, value)
slice([start,] stop [,step])
str(obj)
tuple(s)
type(obj)
vars([obj])
xrange([start,] stop [, step])

# Built-in Exceptions
Exception
StandardError
ArithmeticError
LookupError
EnvironmentError
AssertionError
AttributeError
EOFError
FloatingPointError
IOError
ImportError
IndexError
KeyError
KeyboardInterrupt
MemoryError
NameError
NotImplementedError
OSError
OverflowError
RuntimeError
SyntaxError
SystemError
SystemExit
TypeError
ValueError
ZeroDivisionError

# Internal.
>>> a = [1,4,6]
>>> a.__doc__
"list() -> new list\nlist(sequence) -> new list initialized from sequence's items"
>>> class C:
... a = 0
... def work(self):
... print("hello world")
...
>>> c = C()
>>> c.__dict__
{}
>>> C.__dict__
{'a': 0, '__module__': '__main__', 'work': , '__doc__': None}
# There are many other built-in attributes for classes, instances, modules ...

Reference: Python Essential Reference by David M. Beazley

Labels: ,

1 Comments:

  • At 9/14/2006 7:14 PM , Anonymous Anonymous said...

    too bad i'm not familiar with structured programming, can i still learn it base on object-oriented programming?

     

Post a Comment

Subscribe to Post Comments [Atom]

<< Home