and del from not while as elif global or with assert else if pass yield break except import print class exec in raise continue finally is return def for lambda try
常用于逻辑判断的“与”,“或”,“非”运算,类似C语言的“&&”,“||”,“!”
常用于取代try...except...finally这样的错误处理流程以简化语句
>>> a = 1
>>> b = 2
>>> assert(a == b)
Traceback (most recent call last):
File "<pyshell#89>", line 1, in <module>
assert(a == b)
AssertionError
|
>>> a = 1
>>> exec('a = a+1')
>>> print a
2
|
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> x = 0
>>> for i in a:
x = x + i
>>> print x
45
>>> 5 in a
True
|
>>> a = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> b = a
>>> b is a
True
>>> c = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> c is not a
True
|
>>> mycalc = lambda x,y:x+y*x-x
>>> mycalc(1,2)
2
|
>>> a = 5
>>> b = 2
>>> if a != 2 and b != 5:
pass
else:
print str(a)
|
>>> def mydiv(x,y):
if (y == 0):
raise(ZeroDivisionError)
else:
return x/y
>>> mydiv(10,2)
5
>>> mydiv(3,0)
Traceback (most recent call last):
File "<pyshell#192>", line 1, in <module>
mydiv(3,0)
File "<pyshell#189>", line 3, in mydiv
raise(ZeroDivisionError)
ZeroDivisionError
|
>>> def g(n):
for i in range(n):
yield i*i
>>> for i in g(5):
print i,":",
0 : 1 : 4 : 9 : 16 :
>>> t = g(5)
>>> t.next()
0
>>> t.next()
1
>>> t.next()
4
>>> t.next()
9
>>> t.next()
16
|