iDog's Python Guide
Basic Rules
- A statement should be in a line. When it is to be splitted to multiple lines, at the end of each preceding lines, there should be a '\' at the end.
s = a + b
s = a + \
b
- Indentation: indentation indicates the sub level. You can use either certain number of spaces or tabs, and stick to it, but don't mix them. Recommended ones:
- two spaces
- four spaces
- a tab
Basic Data Types
Python is a OO language, everything are objects.
Numbers
- integer
- long integer
- floating point number
- complex number: (2 + 3j)
Strings
'a string'
"a string"
"It's interesting!"
'''He said, "It's
here!"
'''
"""He said, "It's
here!"
"""
"first line\
second line" # no NL is inserted
Raw strings: no escape sequence process. This is especially useful when you write regexp's.
Format: r'...', r"...", R'...', R"..."
r'use \n as new line'
R'use \n as new line'
Unicode string:
u'漢字'
U'漢字'
Literal concatenation:
"What's " "this?" # --> "What's this?"
Operators
+, -, *, /, %
** (power), // (floor division)
<<, >>, &, |, ^, ~
<, >, <=, >=,
=,
not, and, or
in, not in, is, is not
Flow Control
if condition
if <cond>:
<if_block>
[elif <cond>:
<elif_block>]
[else:
<else_block>]
while loop
while <cond>:
<while_block>
[else:
<else_block>]
for loop
for i in <range>:
<for_block>
[else:
<else_block>]
Notes for loops: when loop is breaked, the 'else_block' won't be executed.
Related keywords: break, continue.
Empty block
use
pass
. Example:
if a > 2:
pass
else:
print 'a <= 2'
Functions
def func1():
<body_of_func1>
def func2(a, b):
<body_of_func2>
def func3(a, b = 1): # default argument for b is 1
<body_of_func3>
def func4():
global x # x is defined out of this function
# ...
return x + 1 # return value from function
# keyword arguments:
def func5(a, b = 1, c = 2):
pass
func5(0, c = 0) # func5(0, 1, 0)
func5(c = 1, b = 2, a = 3) # func5(3, 2, 1)
# doc string
def func():
'''This is a dummy function
illustrating doc string.
'''
pass
print func.__doc__
Modules
A module is a component:
- a module is in the format of a file of '.py' type, with all variables and/or functions you want to put in the module
- can import or be imported by other modules
- byte-compiled modules ('.pyc' type) can be imported faster
Build-in variables:
import my_module
mymodule.myfunc()
print mymodule.myvar
Build-in Complex Data Types
Lists
mylist = [1, 2, 3, 'c', 'b', 'a']
first_elem = mylist[0]
size = len(mylist)
for i in mylist:
print i
for i in range(0, len(mylist)):
print mylist[i]
print mylist
mylist.append('new')
del mylist[1]
mylist.sort()
Tuples
immutable lists.
tp = (1, 2, 3, 'c', 'b', 'a')
tp1 = ('x', tp)
tp2 = (tp1, mylist)
c_elem = tp1[1][3]
x_elem = tp1[0]
#format print with tuples
print "%s is %d years old." % ('Chris', 36)
Usage of sequences: strings, lists, tuples
Sequences have following operations:
- indexing operation
- slicing operation (for example, get a sub-string of a string)
mylist = [0, 1, 2, 3, 4]
print mylist[-1] # 4
print mylist[-2] # 3
print mylist[1:3] # 1, 2
print ml[:] # whole list
print ml[1:] # 1, 2, 3, 4
print ml[:3] # 0, 1, 2
# reference and copy
ml1 = mylist # ref
ml2 = mylist[:] # copy
del mylist[0] # ml1 is affected, while ml2 is not
Other usage
str = "abcde"
if str.startswith("ab"): # true
...
if str.find("cd") != -1: # true
...
if 'bcd' in str: # true
...
str.replace('b', 'B')
delimiter = ", ";
mylist = ['Brazil', 'Russia', 'India', 'China']
print "BRICs means " + delimiter.join(mylist)
Dictionaries
hash table containing key-value pairs. Type of a key must be of an immutable type.
dict = {'a':'aaa', 'b':'bbb', 'c':'ccc'}
aaa = dict['a']
dict['d'] = 'ddd'
del dict['a']
if dict.has_key['b']:
...
for k, v in dict.items():
print "%s - %s" % (k, v)
Class
class MyClass:
num = 0 # static variable
def func(self, str): # 'self' is the 'this' pointer
self.str = str # 'self.str': defines an instance variable
def __init__(self, name): # constructor
self.name = name
MyClass.num += 1
def __del__(self): # destructor
MyClass.num -= 1
mc = MyClass('aaa')
mc.func("a string")
MyClass('bbb').func('another string')
Notes:
- everything in class is public
- but, variables with a name starting from '_' is not visible from outside, since it's scrabled.
- all methods are virtual
Inheritance
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def show(self):
print "Name: %s, Age: %d" % (self.name, self.age), # ',' at the end means no line break
class Employee(Person): # inheritance
def __init__(self, name, age, salary):
Person.__init__(self, name, age)
self.salary = salary
def show(self):
Person.show(self)
print ", Salary: %s" % self.salary
p = Person('Mary', 16)
e = Employee('John', 26, 2000)