本文译自https://docs.python.org/2.7/tutorial/。完全是出于个人兴趣翻译的,请勿追究责任。另外,谢绝商业牟利。刊印请与本人和原作者联系,无授权不得刊印,违者必究其责任。如需转发,请注明来源,并保留此行,尊重本人的劳动成果,谢谢。
来源:CSDN博客
作者:奔跑的QQEE
python 版本:2.7.13
(本文有删改)
python更多语法
一、if 语句
python支持 if 语句。例:
>>> x = int(raw_input("Please enter an integer: "))
Please enter an integer: 42
>>> if x < 0:
... x = 0
... print 'Negative changed to zero'
... elif x == 0:
... print 'Zero'
... elif x == 1:
... print 'Single'
... else:
... print 'More'
...
More
elif 语句可以是零个、一个或多个;也可没有else 部分。elif 是 else if 的缩写。另外,条件后面的语句要注意使用缩进。否则会出现缩进错误。
|
正 |
|
误 |
二、for 语句
python 中的for 语句与 C 和 Pascal 的风格不一样。例:
>>> # 声明字符串数组:
... words = ['cat', 'window', 'defenestrate']
>>> for w in words:
... print w, len(w)
...
cat 3
window 6
defenestrate 12
>>> for w in words[:]:
... if len(w) > 6:
... words.insert(0, w)
...
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']
三、range() 函数
range() 函数用于产生一定范围的数。例:
>>> range(10) # 一个参数,0-10的数,公差是1.
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> range(5, 10) # 两个参数,5-10的数,公差是1.
[5, 6, 7, 8, 9]
>>> range(0, 10, 3) # 三个参数,0-10的数,公差是3.
[0, 3, 6, 9]
>>> range(-10, -100, -30) #三个参数,-10 ~ -100,公差是-30.
[-10, -40, -70]
>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
>>> for i in range(len(a)):
... print i, a[i]
...
0 Mary
1 had
2 a
3 little
4 lamb
四、break、continue语句
二者都用于跳出循环。break 在某次跳出循环后便不再继续后面的循环;continue在某次跳出循环后仍继续后面的循环。例:
>>> for n in range(2, 10):
... for x in range(2, n):
... if n % x == 0:
... print n, 'equals', x, '*', n/x
... break
... else:
... print n, 'is a prime number'
...
2 is a prime number
3 is a prime number
4 equals 2 * 2
5 is a prime number
6 equals 2 * 3
7 is a prime number
8 equals 2 * 4
9 equals 3 * 3
>>> for num in range(2, 10):
... if num % 2 == 0:
... print "Found an even number", num
... continue
... print "Found a number", num
Found an even number 2
Found a number 3
Found an even number 4
Found a number 5
Found an even number 6
Found a number 7
Found an even number 8
Found a number 9
五、pass语句
pass 语句表示什么都不做。相当于空。例:
>>> while True: # 空循环
... pass
...
>>> class MyEmptyClass: # 空类
... pass
...
>>> def initlog(*args): # 空方法
... pass
...
六、声明(定义)函数(方法)
如此定义使用函数:
# 例一
>>> def fib(n): # 定义 fib 函数,此函数有一个参数 n.def 是 define的缩写。
... a, b = 0, 1 # 函数体必须缩进,不然会出现缩进错误。
... while a < n:
... print a,
... a, b = b, a+b
...
>>> # 调用函数 fib(n)
... fib(2000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
#例二
>>> def fib2(n):
... result = []
... a, b = 0, 1
... while a < n:
... result.append(a)
... a, b = b, a+b
... return result # 返回 result 的值
...
>>> f100 = fib2(100)
>>> f100 # 输出结果
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
#例三
def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
# 参数有默认值
while True:
ok = raw_input(prompt)
if ok in ('y', 'ye', 'yes'): # in 检测 ok 是否是()中备选值之一。
return True
if ok in ('n', 'no', 'nop', 'nope'):
return False
retries = retries - 1
if retries < 0:
raise IOError('refusenik user')
print complaint
可以这样调用例三中的方法:
- ask_ok(‘Do you reallywant to quit?’)
- ask_ok(‘OK to overwritethe file?’, 2)
- ask_ok(‘OK to overwrite thefile?’, 2, ‘Come on, only yes or no!’)
再看几个例子:
>>>i = 5
>>>def f(arg=i):
... print arg
>>>i = 6
>>>f()
5 # 结果是 5 而不是 6.
>>>def f(a, L=[]):
... L.append(a) # 每次调用此方法都会在 L 中追加 a
... return L
>>>print f(1)
>>>print f(2)
>>>print f(3)
[1]
[1, 2]
[1, 2, 3]
>>>def f(a, L=None):
... if L is None:
... L = [] # 每次调用此方法都会清空 L
... L.append(a)
... return L
>>>print f(1)
>>>print f(2)
>>>print f(3)
[1]
[2]
[3]
七、关键参数
可以通过设定关键参数的方法调用函数。例:
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, "!"
此函数含有一个必要参数(voltage)和三个可选参数(state,action,type)。
可以这样调用此函数:
parrot(1000)
parrot(voltage=1000)
parrot(voltage=1000000, action='VOOOOOM')
parrot(action='VOOOOOM', voltage=1000000)
parrot('a million', 'bereft of life', 'jump')
parrot('a thousand', state='pushing up the daisies')
但不可以这样调用:
parrot()
parrot(voltage=5.0, 'dead')
parrot(110, voltage=220)
parrot(actor='John Cleese')
再看一个错误的调用:
>>> def function(a):
... pass
...
>>> function(0, a=0) # 给 a 赋了多个值,当然会出错。
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: function() got multiple values for keyword argument 'a'
再看一个例子:
>>>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 = sorted(keywords.keys())
... for kw in keys:
... print kw, ":", keywords[kw]
>>>cheeseshop("Limburger", "It's very runny, sir.", # 调用
"It's really very, VERY runny, sir.",
shopkeeper='Michael Palin',
client="John Cleese",
sketch="Cheese Shop Sketch")
-- 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
调用时传递了 6 个参数。其中Limburger是 参数kind的值; shopkeeper ,client,sketch 都未在cheeseshop 函数中定义。所以这三个参数将被存在 **keywords 中。其余两个字符串将被存在 *arguments 中。
八、解析列表或元组中的参数。
假如某个函数需要传多个参数。可以将需要传递的各个参数定义在一个列表中。而后使用 * 得到各个参数。例:
>>> range(3, 6) # 此方法需要两个参数
[3, 4, 5]
>>> args = [3, 6]
>>> range(*args) # 用 * 取得列表中的各个元素值
[3, 4, 5]
也可以将参数定义在元组中。而后使用 ** 得到各个参数。例:
>>> 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 !
九、Lambda 表达式
用关键字 lambda 指定一个匿名函数。例:
>>> def make_incrementor(n):
... return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43
make_incrementor 函数返回的结果是个匿名函数。该函数需要一个参数 x 。因此可以用 f(0) 的形式继续计算。
另一种用法是将函数当参数传递。例:
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
十、大文本字符串
如此用:
>>> def my_function():
... """Do nothing, but document it.
...
... No, really, it doesn't do anything.
... """
... pass
...
>>> print my_function.__doc__
Do nothing, but document it.
No, really, it doesn't do anything.
1
1
1