博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
【Python】【Python语言】Python3.7.2的关键字与保留字
阅读量:2043 次
发布时间:2019-04-28

本文共 7484 字,大约阅读时间需要 24 分钟。

文章目录

本文是学习Python 3 (目前最新是3.7.3rc1版本) 的官方文档时形成的阅读与实验笔记。

Python关键字/保留字

Python 3文档中记述的关键字/保留字列表:

保留字(reserved words)是Python语言预先保留的标识符(identifier),这些标识符在Python程序中具有特定用途,不能被程序员作为常规变量名,函数名等使用。

关键字(keyword)是Python语言目前正在使用的保留字。目前未被使用的保留字,在未来版本中可能被使用,成为关键字。

注意:Python的保留字是大小写敏感的;除了True、False和None这三个字以外,其他的保留字都是小写单词。

打印Python关键字/保留字列表

从下面的列表中可以看出,相比Python 3.6版的33个关键字,Python 3.7版本中正式引入两个新的关键字async与await,共35个关键字。

import keywordprint(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']

Python保留字简介

True与False

布尔类型变量的取指,True表示真,False表示假,例如

is_male = Trueis_female = False

if、elif与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!")

in

用于测试某个值是否位于列表中。

5 in [5, 6, 7]

del

del用于删除一个变量,或者删除list中的某个元素。

a = "Hello"b = adel a # delete variable aprint(b) # we can still print bl = [1, 3, 5, 7]del l[1] # delete the 2nd elementprint(l) # expect to print out [1, 5, 7]
--- Console Output ---Hello[1, 5, 7]

for/while与break

for与while用于构造循环语句,continue用于跳过循环内后续语句,立即开始执行下一次循环迭代,break用于退出循环语句(通常在循环语句正常结束前),例如

# for loop with continue/breakfor 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/breaki = 5while i < 10:    print(i)    i += 1    if i == 5:        continue # skip the first element    if i == 8:        break # end the loop

and,or与not

and操作符是对两个布尔值做“与”操作,结果是布尔值

or操作符是对两个布尔值做“或”操作,结果是布尔值
not操作符是对布尔值做“取非”操作,结果是布尔值

is_male = Trueis_tall = Falseis_tall_and_male = is_male and is_tallis_tall_or_male = is_male or is_tallis_not_male = not is_maleprint(is_tall_and_male, is_tall_or_male, is_not_male)

def, return与yield

def用于定义函数,return用于从函数中返回,可以带有一个值。

yield用于生成器,当函数中使用yield时,Python解释器会将函数解释为生成器。

# two functions with returndef foo():    print("in function foo()")    return # simple returndef square(num):    return num*num # return a value foo()print(square(5))
# a generator with yielddef 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 iterationfor n in fib(15):    print (n)

class

class用于定义类,用于面向对象的程序设计。

class Dog:    def __init__(self, name):        self.__name = name    def bark(self):        print(self.__name + " is barking.")mydog = Dog("Bob")mydog.bark()

from, import与as

from $package.$module import $class as $new_class

表从 $package.$module 中导入 $class,as指定别名 $new_class,程序调用时,使用别名。

from math import pow as pprint(p(2,3))

assert

assert后面的表达式会计算出一个布尔值,如果为True,则断言成立,程序继续执行;如果为False,则立刻停止程序运行,打印AssertError,以及assert中指定的字符串消息。

assert语句通常用于程序的调试版本,用于断言本应该为True的条件。如果条件不成立,通常认为出现了bug,或者输入错误,assert语句可以在最近的地方停下来让程序员进行检查。注意:assert语句不是用来替代if判断语句的。

x = 4assert 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 
assert x % 2 == 1, "x is not an odd number"AssertionError: x is not an odd number

is

is主要用于判断两个变量是否引用同一个对象,即对象的id相同。如果是则返回True,否则返回False。

x = 4y = 4z = 5print("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 1569055552y is at 1569055552z is at 1569055568x is y:Truey is z:Falsex is z:False

pass

pass是空语句,不做任何事情,一般用于做占位符,保持程序结构完整。

x = 5if x > 3:    print("x > 3")else:    pass # this is a placeholder for future

None

None表示变量是空值,有点类似于C语言的NULL。None实际上是NoneType类的示例。

print(type(None))x = Noney = 5if x is None:    print("x is None")if y is not None:    print("y is not None")
--- Console Output ---
x is Noney is not None

try, except, else与finally

try用于捕获后面的语句可能产生的异常;当出现异常时,则执行except后面的语句;没有异常则执行else后面的语句;无论是否出现异常,都是执行finally后面的语句。

交叉参考:。

x = 0try:    print("Let's try 0 / 0")    x = x / 0except:    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 / 1except:    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 / 0I caught an exceptionThis line is from always-executed finally blockLet's try 0 / 1Luckily, there is no exceptionThis line is from always-executed finally block

with与as

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/fstabwith 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 installationUUID=a586a207-1142-456e-aa2e-fe567327344b / ext4 errors=remount-ro 0 1# swap was on /dev/sda5 during installationUUID=d507d3f1-20db-4ad6-b12e-e83ecee49398 none swap sw 0 0

global

global定义通知Python后面的变量是全局变量,不要定义出一个新的局部变量。

x = 6def 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 = 7global x = 6x in func = 7global x = 7

nonlocal

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():xfoo()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 = 6foo2():x = 7

lambda

lambda用于定义一个表达式,实际上相当于定义了一个匿名函数。

# x, y are input parameters : return x + yg = lambda x, y: x + yprint(g(1,2)) # number 1 + 2, return 3print(g("2","4")) # string "2" + "4", return "24"print(g(True, True)) # bool True + True, return 2
--- Console Output ---3242

await与async

转载地址:http://bppof.baihongyu.com/

你可能感兴趣的文章
Linux下查看根目录各文件内存占用情况
查看>>
A星算法详解(个人认为最详细,最通俗易懂的一个版本)
查看>>
利用栈实现DFS
查看>>
逆序对的数量(递归+归并思想)
查看>>
数的范围(二分查找上下界)
查看>>
算法导论阅读顺序
查看>>
Windows程序设计:直线绘制
查看>>
linux之CentOS下文件解压方式
查看>>
Django字段的创建并连接MYSQL
查看>>
div标签布局的使用
查看>>
HTML中表格的使用
查看>>
(复健计划)python中元祖的一系列操作
查看>>
(复健计划)python中的字典
查看>>
(复健计划)python中的正则表达式
查看>>
(复健计划)python面向对象
查看>>
(复健计划)python函数
查看>>
C++Lambda表达式
查看>>
类的静态成员
查看>>
操作符重载(类里面和类外面)
查看>>
CentOS7设置开机启动方式(图形界面/命令行界面
查看>>