keyword | usage | expression format | example |
---|---|---|---|
Fasle | 布尔值 | x = 1 print(x == 0) #打印Fasle | |
True | 布尔值 | x = 0 print(x == 0) #打印True | |
and | 逻辑与&& | if x!=0 and y!=0: print("pass") | |
as | 给模块取别名 | import keyword as k print(k.kwlist) | |
assert | 断言 | assert(ret == 0) #当ret不等于0时程序抛出AssertionError | |
break | 终止循环 | for i in range(10): if x%i == 0: break | |
continue | 跳过本次循环的部分语句 | line_num = 0 for line in f: if len(line)==0: continue #不执行下一行,进入下一次循环 line_num += 1 | |
def | 定义函数 | def max(x, y): if x>=y: return x return y | |
del | 删除对象 | ls = [1,2,3,4] del ls[-1] #删除列表的最后一个元素 | |
elif | 条件语句,与if搭配使用 | if grade >= 90: print("成绩优秀") elif grade >= 80: print("成绩良好") | |
else | 条件语句的其他情况,与if搭配使用 | if x>=0: print("非负数") else: print("负数") | |
except | 捕获异常,与try搭配使用 | x = 3 y = 0 try: x/y except: print("division error") | |
for | 循环 | ls = [1,2,3,4] for i in ls: print(i) #遍历列表并打印 | |
from | 导入模块的特定部分 | from scipy.misc import imread mask = imread("xxx.png") | |
global | 声明全局变量 | s = 0 def add_num(num): global s #表明这是全局变量s s += num add_num(10) | |
if | 条件语句 | if x>y: print("x>y") | |
import | 导入模块 | import cv2 cap = cv2.VideoCapture(0) | |
in | 检查是否在某个容器中 | ls = ['1', '2', '3', '4'] print('1' in ls) | |
is | 判断两个对象是否为同一个 | ls = ['1', '2', '3'] lt = ls ln = ls.copy() print(lt is ls) #True print(ln is ls) #False | |
lambda | 用于创建小型匿名函数,返回一个函数对象 | lamda [arguments]: expression | def f(): return lambda x,y:x+y add = f() add(1,2) |
not | 逻辑非 ! | n=1 if not n == 0: print("n is non-zero") | |
or | 逻辑或 || | gender = "none" if gender == "female" or gender == "male": print("it is human") | |
return | 函数返回 | def add(a, b): return a+b c = add(a, b) | |
try | 捕获异常 | try: open("dshakdjfsk.txt") execpt: print("fail to open specified file") | |
while | 循环 | i = 0 while (i < 10): print(i) i += 1 |