[Src: Python 2.5 Document]
1. if-statement
与C/C++不同的是,Python中 if 或 elif 要以 : 结尾
Code
>>> x = int(raw_input("Please enter an integer: "))
>>> if x < 0:
x = 0
print 'Negative changed to zero'
elif x == 0:
print 'Zero'
elif x == 1:
print 'Single'
else:
print 'More'
2. for-statement
iterates over the items of any sequence(a list or a string)
Code
>>> # Measure some strings:
a = ['cat', 'window', 'defenestrate']
>>> for x in a:
print x, len(x)
cat 3
window 6
defenestrate 12
若要修改序列中的内容,就只能在序列的副本上遍历。这里只能修改list的内容
Code
>>> for x in a[:]: # make a slice copy of the entire list
if len(x) > 6: a.insert(0, x)
>>> a
['defenestrate', 'cat', 'window', 'defenestrate']
3. range()
a) range(10) ==> [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
b) range(5, 10) ==> [5, 6, 7, 8, 9]
c) range(-10, -100, -30) ==> [-10, -40, -70]
4. else clause
Loop statements may have an else
clause; it is executed when the loop terminates through exhaustion of the list (with for) or when the condition becomes false (with while), but not when the loop is terminated by a break statement.
即,当循环正常结束后,才会走到else语句中;如果循环被break掉,则跳过else
Code
>>> for n in range(2, 10):
for x in range(2, n):
if n % x == 0:
print n, 'equals', x, '*', n/x
break
else:
# loop fell through without finding a factor
print n, 'is a prime number'
5. pass-statement
空语句,语法要求
6. Defining functions
def func_name(parameter1, parameter2,...)
函数参数的解析顺序:local symbol table -> global symbol table -> built-in symbol table
通常情况下只能在函数中访问global的变量,但无法修改其值。除非用global显式声明
a) Default Argument Values
从左到右的顺序,如果某个参数设有默认值,则其后的所有参数都必须设有默认值,与C++类似
Code
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
while True:
ok = raw_input(prompt)
if ok in ('y', 'ye', 'yes'): return True
if ok in ('n', 'no', 'nop', 'nope'): return False
retries = retries - 1
if retries < 0: raise IOError, 'refusenik user'
print complaint
Default Value只会被赋值一次,因此可以对同一个函数,后续的调用会使用到前次调用的结果
Code
def f(a, L=[]):
L.append(a)
return L
print f(1)
print f(2)
print f(3)
# result
[1]
[1, 2]
[1, 2, 3]
消除此种影响的方法:
Code
def f(a, L=None):
if L is None:
L = []
L.append(a)
return L
b) Keyword Arguments
允许以 "keyword = argument" 的方式传参。此时,传参的顺序不必遵守定义的顺序。No argument may receive a value more than once
注意:如果未以这种方式传参,则按照从左到右顺序赋值。一旦某个参数以keyword方式传参,则其后所有参数也必须采用此种方法
Code
def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
print "-- This parrot wouldn't", action,
print "if you put", voltage, "volts through it."
print "-- Lovely plumage, the", type
print "-- It's", state, "!"
# right
parrot(1000)
parrot(action = 'VOOOOOM', voltage = 1000000)
parrot('a thousand', state = 'pushing up the daisies')
parrot('a million', 'bereft of life', 'jump')
# wrong
parrot() # required argument missing
parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
parrot(110, voltage=220) # duplicate value for argument
parrot(actor='John Cleese') # unknown keyword
**parameter: 接受一个dictionary(包含一组keyword arguments)
*parameter: the positional arguments beyond the formal parameter list。不能接受keyword arguments参数
如果两者一起使用,则*parameter必须出现在**parameter之前
Code
def cheeseshop(kind, *arguments, **keywords):
print "-- Do you have any", kind, '?'
print "-- I'm sorry, we're all out of", kind
for arg in arguments: print arg
print '-'*40
keys = keywords.keys()
keys.sort()
for kw in keys: print kw, ':', keywords[kw]
#test
cheeseshop('Limburger', "It's very runny, sir.",
"It's really very, VERY runny, sir.",
client='John Cleese',
shopkeeper='Michael Palin',
sketch='Cheese Shop Sketch')
#resule
-- Do you have any Limburger ?
-- I'm sorry, we're all out of Limburger
It's very runny, sir.
It's really very, VERY runny, sir.
----------------------------------------
client : John Cleese
shopkeeper : Michael Palin
sketch : Cheese Shop Sketch
c) Arbitrary Argument Lists
Code
def fprintf(file, format, *args):
file.write(format % args)
d) Unpacking Argument Lists
如果参数已经存于list或tuple中,则用*来展开参数
如果参数存于dictionary中,则用**
Code
# *-operator
>>> args = [3, 6]
>>> range(*args) # call with arguments unpacked from a list
[3, 4, 5]
# **-operator
>>> def parrot(voltage, state='a stiff', action='voom'):
print "-- This parrot wouldn't", action,
print "if you put", voltage, "volts through it.",
print "E's", state, "!"
>>> d = {"voltage": "four million", "state": "bleedin' demised", "action": "VOOM"}
>>> parrot(**d)
-- This parrot wouldn't VOOM if you put four million volts through it. E's bleedin' demised !
e) Lambda Forms
(与函数编程语言类似的功能?)像个函数
Code
>>> def make_incrementor(n):
return lambda x: x + n
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43