1.False 4.class 6.finally 17.is 10.return
2.None 9.continue 8.for 21.lambda 5.try
1.True 10.def 11.from 15.nonlocal 8.while
3.and 13.del 14.global 3.not 19.with
19.as 8.elif 8.if 3.or 20.yield
12.assert 8.else 11.import 16.pass
9.break 5.except 18.in 7.raise
False True
布尔类型的值,表示真假,用于判断
None
None是一个特殊的常量。None和False不同。None不是0。None不是空字符串。None和任何其他的数据类型比较永远返回False。None有自己的数据类型NoneType。你可以将None复制给任何变量,但是你不能创建其他NoneType对象
>>> type(None)
<class 'NoneType'>
>>> None == 0
False
>>> None == ''
False
>>> None == None
True
>>> None == False
False
and or not
逻辑运算符,与或非
class
定义类的关键字
try except
异常处理关键字,一般连用,用来捕获异常
try:
block
except [exception,[data…]]:
block
try:
block
except [exception,[data...]]:
block
else:
block
try:
f = open('xxx')
except:
do something
finally:
f.close()
class MyException(Exception):pass
try:
#some code here
raise MyException
except MyException:
print "MyException encoutered"
finally:
print "Arrive finally"
for while if else elif
for while循环关键字
if 条件判断关键字
else 可与上面两个连用,代表否则
elif 是else if的缩写
break continue
break continue都是终止循环
但break 是直接退出循环
而continue是终止当前这一次循环,继续后面的循环
def return
def 为定义函数的关键字,return语句用来从一个函数 返回 即跳出函数。我们也可选从函数 返回一个值
from import
在python中用from 或from … import … 导入相关模块,函数
assert
断言,这个关键字用来在运行中检查程序的正确性,条件判断错误会产生异常,和很多其他语言是一样的作用。如
assert len(mylist) >= 1
a = [-1, 3,'aa', 85] # 定义一个list
del a[0] #删除第0个元素
del a[2:4] #删除从第2个元素开始,到第4个为止的元素。包括头不包括尾
#定义全局变量,变量名全部大写
NAME = "stormjing"
#得到NAME值
def get_NAME():
return NAME
#重新设定NAME值
def set_NAME(name_value):
global NAME
NAME = name_value
print u"输出全局变量NAME的值:",get_NAME()
new_name = "521stormjing"
set_NAME(new_name)#为全局变量重新赋值
print u"输出赋值完的全局变量NMAE的值:",get_NAME()
def make_counter():
count = 0
def counter():
nonlocal count
count += 1
return count
return counter
def make_counter_test():
mc = make_counter()
print(mc())
print(mc())
print(mc())
def test_pass():pass #如果不加pass,抛出错误:IndentationError: expected an indented block
test_pass()
>>> a = 1
>>> b = 1.0
>>> a is b
False
>>> a == b
True
>>> id(a)
>>> id(b)
first_list = [1, 2]
second_list = [1, 2, 3]
element = 1
red = 'red'
red_clothes = "red clothes"
print red in red_clothes #true
print first_list in second_list #false
print element in first_list #true
class Sample:
def __enter__(self):
print "In __enter__()"
return "Foo"
def __exit__(self, type, value, trace):
print "In __exit__()"
def get_sample():
return Sample()
with get_sample() as sample:
print "sample:", sample
输出结果:
In __enter__()
sample: Foo
In __exit__()
#理解yield
def test_yield(n):
for i in range(n):
yield i*2#每次的运算结果都返回
for j in test_yield(8):
print j,":",
print u"结束理解yield"
#利用yield输出斐波那契数列
def fab(max):
a,b = 0,1
while a < max:
yield a
a, b = b, a+b
print "斐波那契数列!"
for i in fab(20):
print i,",",
g = lambda :"lambda test."
print g()
num1 = lambda x, y=1:x + y
print num1(1) #多个变量的时候,可以不给有默认值的变量传值
print num1(10,10) #值得注意的是,如果y没有默认值而且不给它传值的话报错