文章目录

  • Python关键字/保留字
  • 打印Python关键字/保留字列表
  • Python保留字简介
    • True与False
    • if、elif与else
    • in
    • del
    • for/while与break
    • and,or与not
    • def, return与yield
    • class
    • from, import与as
    • assert
    • is
    • pass
    • None
    • try, except, else与finally
    • with与as
    • global
    • nonlocal
    • lambda
    • await与async

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

Python关键字/保留字

Python 3文档中记述的关键字/保留字列表:https://docs.python.org/3/reference/lexical_analysis.html#keywords

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

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

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

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

从下面的列表中可以看出,相比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']

Python保留字简介

True与False

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

is_male = True
is_female = False

if、elif与else

交叉参考:else用于异常捕获语句中。
用于构造条件分支语句,例如

if is_male:print("You are a man.")
elif is_female:print("You are a woman.")
elseprint("You are in the 3rd-gender!")

in

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

5 in [5, 6, 7]

del

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

a = "Hello"
b = adel a # delete variable a
print(b) # we can still print bl = [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与break

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

# for loop with continue/break
for i in [5, 6, 7, 8, 9]:if i == 5:continue # skip the first elementif i == 8:break; # end the loopprint(i)
# while loop with continue/break
i = 5
while i < 10:print(i)i += 1if i == 5:continue # skip the first elementif i == 8:break # end the loop

and,or与not

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

is_male = True
is_tall = Falseis_tall_and_male = is_male and is_tall
is_tall_or_male = is_male or is_tall
is_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 return
def foo():print("in function foo()")return # simple returndef square(num):return num*num # return a value foo()
print(square(5))
# a generator with yield
def fib(max):a, b = 1, 1while a < max:yield a # stop here and return aa, 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 = namedef 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 p
print(p(2,3))

assert

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

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

x = 4
y = 4
z = 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 1569055552
y is at 1569055552
z is at 1569055568
x is y:True
y is z:False
x 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 = 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

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 blockLet's try 0 / 1
Luckily, there is no exception
This 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/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).
#
# <file system> <mount point>   <type>  <options>       <dump>  <pass>
# / 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

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

x = 6
def local_x():x = 7 # acutally defined a new local variable xprint("x in func = " + str(x))local_x()
print("global x = " + str(x))print("")def global_x():global x # tell python x is globalx = 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 = 6x in func = 7
global x = 7

nonlocal

nonlocal是Python3新增的关键字,用于告知Python后面的变量定义在其他地方,不要在本函数中定义出一个新的局部变量。

def foo():x = 6 # this is a local variable in foodef change_foo_x():x = 7 # intend to change the x defined in foo(), but will failchange_foo_x()print("foo():x = " + str(x)) # actually failed to change foo():xfoo()print("")
def foo2():x = 6 # this is a local variable in foo2def change_foo2_x():nonlocal x # search upwards for the x variablex = 7 # change the x defined in foo2(), and will succeedchange_foo2_x()print("foo2():x = " + str(x))foo2()
--- Console Output ---
foo():x = 6foo2():x = 7

lambda

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

await与async

廖雪峰老师的官方网站 aysnc/await介绍

【Python】【Python语言】Python3.7.2的关键字与保留字相关推荐

  1. 判断mysql的关键字_MySQL关键字以及保留字

    开发过程中可打开此页面,使用CTRL+F进行搜索,如有字段名与MySQL关键字或保留字相同,应尽量避免使用. 也可以用以下python程序判断单词是否为MySQL关键字或者保留字. import sy ...

  2. Python:Python语言的简介(语言特点/pyc介绍/Python版本语言兼容问题(python2 VS Python3))、安装、学习路线(数据分析/机器学习/网页爬等编程案例分析)之详细攻略

    Python:Python语言的简介(语言特点/pyc介绍/Python版本语言兼容问题(python2 VS Python3)).安装.学习路线(数据分析/机器学习/网页爬等编程案例分析)之详细攻略 ...

  3. Python语言的简介(语言特点/pyc介绍/Python版本语言兼容问题(python2 VS Python3))、安装、学习路线(数据分析/机器学习/网页爬等编程案例分析)之详细攻略

    目录 Python语言的简介 1.Python的应用领域 2.Python语言特点.对比其它语言 2.1.Python语言特点 2.2.Python语言对比其它语言 3.Python版本语言兼容问题( ...

  4. python语言中不用来定义函数的关键字_Python 语言中用来定义函数的关键字是

    Python 语言中用来定义函数的关键字是 答:def 调查问卷采集是数据采集人员通过设计具有针对性的问卷,采用方式进行信息采集 答:以上都是 中国大学MOOC: 突出重点,必须以解决问题为目标.也就 ...

  5. python中def和return是必须使用的保留字吗_Python 保留字和关键字的用法

    Python 保留字和关键字的用法 详解 学习python3的一些总结 Python3文档中详细介绍: https://docs.python.org/3/reference/lexical_anal ...

  6. 轻松玩转AI(从Python开始之Python3入门)

    轻松玩转AI路径: 从Python开始 [链接] 数据科学 [链接] 机器学习 [链接] 深度学习--神经网络 [链接] 从Python开始: Python3入门 [链接] Python3进阶 [链接 ...

  7. 各种编程语言功能综合简要介绍(C,C++,JAVA,PHP,PYTHON,易语言)

    各种编程语言功能综合简要介绍(C,C++,JAVA,PHP,PYTHON,易语言) 总结 a.一个语言或者一个东西能火是和这种语言进入某一子行业的契机有关.也就是说这个语言有没有解决社会急需的问题. ...

  8. python return用法_Python 为什么没有 void 关键字?

    void 是编程语言中最常见的关键字之一,从字面上理解,它是"空的.空集.空白"的意思,最常用于表示函数的一种返回值类型. 维基百科上有一个定义: The void type, i ...

  9. Supporting Python 3(支持python3)——为Python 3做准备

    2019独角兽企业重金招聘Python工程师标准>>> 为Python3作准备 在开始添加Python 3的支持前,为了能够尽可能地顺利过度到Python 3,你应该通过修改对2to ...

最新文章

  1. mysql cluster_redislt;3.cluster集群模式gt;
  2. 如何避免开发一款失败的产品?
  3. php 正则 回溯,php 正则表达式效率 贪婪、非贪婪与回溯分析
  4. 人物角色群体攻击判定二(叉乘来判断敌人的位置)
  5. 推荐一个牛逼的生物信息 Python 库 - Dash Bio
  6. python的匿名函数返回值_Python匿名函数返回值输出问题望指点
  7. HDU 1411--校庆神秘建筑(欧拉四面体体积计算)
  8. 古剑2计算机中丢失,小编研习win7系统玩古剑奇谭2提示计算机中丢失Vcomp100.dl的图文方法...
  9. Linux---单例模式
  10. UVA11554 Hapless Hedonism【数学计算+大数】
  11. c++中的构造函数和析构函数
  12. SQL Server2005如何进行数据库定期备份
  13. Windows内核结构
  14. VC6.0下载及安装
  15. 计算机word设置渐变填充,word文本效果在哪里?怎么设置填充渐变颜色?
  16. STM32F103ZET6【标准库函数开发】-----TM1638模块驱动4位8段共阴极数码管
  17. CytusII 剧情梳理
  18. dubbo源码分析-dubbo-serialization
  19. VTT字幕文件处理(vi + sed + awk)
  20. 一款清爽的CSS表格样式

热门文章

  1. pytorch 之 imagefloder的用法
  2. PyQt5学习笔记(二) 文本控件及使用
  3. Chromium版Edge体验——几个理由告诉你为什么卸载Chrome!
  4. poj 3414 Pots BFS
  5. leetcode206题:反转链表(迭代或是递归)
  6. 小程序开发代码_企业为什么要选择小程序定制开发?
  7. nexbox本地网络调试工具下载_「下载」 Windows 10 WinDBG 分析转储日志和蓝屏日志排查错误原因...
  8. 计算机科学NIP,焦点:网络入侵防护(NIP)技术真的成了鸡肋吗? -电脑资料
  9. python开发环境有哪些_python编程需要什么环境
  10. pythongui做计算器_python GUI之简易计算器