if x==y: do_x_equal_y_stuff() elif x==z: do_x_equal_z_stuff() else: do_other_stuff()
循环
for-loop.py
1 2 3 4 5 6 7 8 9
for i in range(5): print i if i == j: break if i == k: continue else: # do something if the loop end normally do_some_stuff()
while-loop.py
1 2 3 4 5 6 7 8 9 10
while x>0: x-- print x if x == j: break if x == k: continue else: #do something if the loop end normally do_some_stuff()
函数
simple-function.py
1 2 3 4 5 6
defadd(a,b): ''' return the result of a plus b'''# docstring, need to be at the first line of the function return a+b
#call the function print add(1,3)
local-global.py
1 2 3 4 5 6 7 8 9 10 11
x=10# Here, x is global deffoo(): x = 50# Here, x is local, does not affect the global x defbar(): global x x= 8# Here, x is global # test foo() print x bar() print x
default-parameters.py
1 2 3 4 5 6 7
defadd(a, b, c=0, d=3): return a+b+c+d
#call the function print add(1, 3) print add(1, 3, 4) print add(1, 3, d=2)
list-and-dict-parameters.py
1 2 3 4 5 6 7 8 9
deffoo(a, *l, **d): print a for list_item in l: print list_item for key,value in d: print"{k}:{v}".format(k=key, v=value)
__metaclass__ = type classFib: def__init__(self): self.first = 1 self.second = 1 def__iter__(self): return self # a iterator returns a object which implements the 'next' method defnext(self):# if there is no next item, raise 'StopIteration' exception ret = self.first tmp = self.second self.second = self.second + self.first self.first = tmp return ret
deffoo(parameters): try: # do something if someCondition : raise SomeError if someOtherCondition: raise someErrorObject # do something except SomeError: raise# raise the exception again except (SomeError1, SomeError2): # catch two types of exceptions at the same site # do something except (SomeError3), errorObject: # do something with errorObject except: # catch all exceptions else: # do something if no exception is raised finally: # do something whether there is any exception or not