Python 3文档中记述的关键字/保留字列表:https://docs.python.org/3/reference/lexical_analysis.html#keywords
保留字(reserved words)是Python语言预先保留的标识符(identifier),这些标识符在Python程序中具有特定用途,不能被程序员作为常规变量名,函数名等使用。
关键字(keyword)是Python语言目前正在使用的保留字。目前未被使用的保留字,在未来版本中可能被使用,成为关键字。
注意:Python的保留字是大小写敏感的;除了True、False和None这三个字以外,其他的保留字都是小写单词。
从下面的列表中可以看出,相比Python 3.6版的33个关键字,Python 3.7版本中正式引入两个新的关键字async与await,共35个关键字。
import keyword
print(keyword.kwlist)
--- Python 3.6 Console Output ---
['False', 'None', 'True', 'and', 'as', 'assert',
'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global',
'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']
--- Python 3.7 Console Output ---
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await',
'break', 'class', 'continue', 'def', 'del', 'elif',
'else', 'except', 'finally', 'for', 'from', 'global',
'if', 'import', 'in', 'is', 'lambda', 'nonlocal',
'not', 'or', 'pass', 'raise', 'return', 'try',
'while', 'with', 'yield']
布尔类型变量的取指,True表示真,False表示假,例如
is_male = True
is_female = False
交叉参考:else用于异常捕获语句中。
用于构造条件分支语句,例如
if is_male:
print("You are a man.")
elif is_female:
print("You are a woman.")
else
print("You are in the 3rd-gender!")
用于测试某个值是否位于列表中。
5 in [5, 6, 7]
del用于删除一个变量,或者删除list中的某个元素。
a = "Hello"
b = a
del a # delete variable a
print(b) # we can still print b
l = [1, 3, 5, 7]
del l[1] # delete the 2nd element
print(l) # expect to print out [1, 5, 7]
--- Console Output ---
Hello
[1, 5, 7]
for与while用于构造循环语句,continue用于跳过循环内后续语句,立即开始执行下一次循环迭代,break用于退出循环语句(通常在循环语句正常结束前),例如
# for loop with continue/break
for i in [5, 6, 7, 8, 9]:
if i == 5:
continue # skip the first element
if i == 8:
break; # end the loop
print(i)
# while loop with continue/break
i = 5
while i < 10:
print(i)
i += 1
if i == 5:
continue # skip the first element
if i == 8:
break # end the loop
and操作符是对两个布尔值做“与”操作,结果是布尔值
or操作符是对两个布尔值做“或”操作,结果是布尔值
not操作符是对布尔值做“取非”操作,结果是布尔值
is_male = True
is_tall = False
is_tall_and_male = is_male and is_tall
is_tall_or_male = is_male or is_tall
is_not_male = not is_male
print(is_tall_and_male, is_tall_or_male, is_not_male)
def用于定义函数,return用于从函数中返回,可以带有一个值。
yield用于生成器,当函数中使用yield时,Python解释器会将函数解释为生成器。
# two functions with return
def foo():
print("in function foo()")
return # simple return
def square(num):
return num*num # return a value
foo()
print(square(5))
# a generator with yield
def fib(max):
a, b = 1, 1
while a < max:
yield a # stop here and return a
a, b = b, a + b # continue from here for next iteration
for n in fib(15):
print (n)
class用于定义类,用于面向对象的程序设计。
class Dog:
def __init__(self, name):
self.__name = name
def bark(self):
print(self.__name + " is barking.")
mydog = Dog("Bob")
mydog.bark()
from $package.$module import $class as $new_class
表从 $package.$module 中导入 $class,as指定别名 $new_class,程序调用时,使用别名。
from math import pow as p
print(p(2,3))
assert后面的表达式会计算出一个布尔值,如果为True,则断言成立,程序继续执行;如果为False,则立刻停止程序运行,打印AssertError,以及assert中指定的字符串消息。
assert语句通常用于程序的调试版本,用于断言本应该为True的条件。如果条件不成立,通常认为出现了bug,或者输入错误,assert语句可以在最近的地方停下来让程序员进行检查。注意:assert语句不是用来替代if判断语句的。
x = 4
assert x % 2 == 1, "x is not an odd number"
--- console output ---
Traceback (most recent call last):
File "C:/Users/tsu5/PycharmProjects/HelloWorld/hello.py", line 2, in <module>
assert x % 2 == 1, "x is not an odd number"
AssertionError: x is not an odd number
is主要用于判断两个变量是否引用同一个对象,即对象的id相同。如果是则返回True,否则返回False。
x = 4
y = 4
z = 5
print("x is at " + str(id(x)))
print("y is at " + str(id(y)))
print("z is at " + str(id(z)))
print("x is y:" + str(x is y))
print("y is z:" + str(y is z))
print("x is z:" + str(x is z))
--- Console Output ---
x is at 1569055552
y is at 1569055552
z is at 1569055568
x is y:True
y is z:False
x is z:False
pass是空语句,不做任何事情,一般用于做占位符,保持程序结构完整。
x = 5
if x > 3:
print("x > 3")
else:
pass # this is a placeholder for future
None表示变量是空值,有点类似于C语言的NULL。None实际上是NoneType类的示例。
print(type(None))
x = None
y = 5
if x is None:
print("x is None")
if y is not None:
print("y is not None")
--- Console Output ---
<class 'NoneType'>
x is None
y is not None
try用于捕获后面的语句可能产生的异常;当出现异常时,则执行except后面的语句;没有异常则执行else后面的语句;无论是否出现异常,都是执行finally后面的语句。
交叉参考:else用于if语句中。
x = 0
try:
print("Let's try 0 / 0")
x = x / 0
except:
print("I caught an exception")
else:
print("Luckily, there is no exception")
finally:
print("This line is from always-executed finally block")
print("")
try:
print("Let's try 0 / 1")
x = x / 1
except:
print("I caught an exception")
else:
print("Luckily, there is no exception")
finally:
print("This line is from always-executed finally block")
--- Console Output ---
Let's try 0 / 0
I caught an exception
This line is from always-executed finally block
Let's try 0 / 1
Luckily, there is no exception
This line is from always-executed finally block
with语句由Python 2.5开始引入,需要通过下面的import语句导入才可以使用。
from __future__ import with_statement
到了Python2.6,则正式引入,默认可用,无需额外的导入语句。
with语句与“上下文管理器”这个概念密切相关。只有支持上下文管理器的对象,才可以使用with语句进行处理。本文不详细介绍上下文管理器,仅说明支持上下文管理器的对象都会实现__enter__()与__exit()__方法。
with与as的基本语句格式如下:
with context_expression [as target(s)]:
with-statements
当with语句进入时,会执行对象的__enter__()方法,该方法返回的值会赋值给as指定的目标;当with语句退出时,会执行对象的__exit__()方法,无论是否发生异常,都会进行清理工作。
# print out every line in /etc/fstab
with open(r'/etc/fstab') as f:
for line in f:
print(line, end="")
--- Console Output ---
# /etc/fstab: static file system information.
#
# Use 'blkid' to print the universally unique identifier for a
# device; this may be used with UUID= as a more robust way to name devices
# that works even if disks are added and removed. See fstab(5).
#
#
# / was on /dev/sda1 during installation
UUID=a586a207-1142-456e-aa2e-fe567327344b / ext4 errors=remount-ro 0 1
# swap was on /dev/sda5 during installation
UUID=d507d3f1-20db-4ad6-b12e-e83ecee49398 none swap sw 0 0
global定义通知Python后面的变量是全局变量,不要定义出一个新的局部变量。
x = 6
def local_x():
x = 7 # acutally defined a new local variable x
print("x in func = " + str(x))
local_x()
print("global x = " + str(x))
print("")
def global_x():
global x # tell python x is global
x = 7 # not define a new local variable. changing global variable.
print("x in func = " + str(x))
global_x()
print("global x = " + str(x))
--- Console Output ---
x in func = 7
global x = 6
x in func = 7
global x = 7
nonlocal是Python3新增的关键字,用于告知Python后面的变量定义在其他地方,不要在本函数中定义出一个新的局部变量。
def foo():
x = 6 # this is a local variable in foo
def change_foo_x():
x = 7 # intend to change the x defined in foo(), but will fail
change_foo_x()
print("foo():x = " + str(x)) # actually failed to change foo():x
foo()
print("")
def foo2():
x = 6 # this is a local variable in foo2
def change_foo2_x():
nonlocal x # search upwards for the x variable
x = 7 # change the x defined in foo2(), and will succeed
change_foo2_x()
print("foo2():x = " + str(x))
foo2()
--- Console Output ---
foo():x = 6
foo2():x = 7
lambda用于定义一个表达式,实际上相当于定义了一个匿名函数。
# x, y are input parameters : return x + y
g = lambda x, y: x + y
print(g(1,2)) # number 1 + 2, return 3
print(g("2","4")) # string "2" + "4", return "24"
print(g(True, True)) # bool True + True, return 2
--- Console Output ---
3
24
2
廖雪峰老师的官方网站 aysnc/await介绍