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

Python 保留字和关键字的用法 详解

学习python3的一些总结

Python3文档中详细介绍: https://docs.python.org/3/reference/lexical_analysis.html#keywords

概念:保留字是python语言预先保留的标识符,在程序中有特定用途,不能用来作为变量名,函数名使用;保留字大小写敏感,除开 False,True,None

python获取关键字列表

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']

保留字详解

1、True和False

布尔类型变量取值,True为真,False为假

is_1 = True

is_2 = False

2、if, elif 和else

判断语句,条件分支语句

if score < 60:

print(“不及格”)

elif score < 80:

print("不够优秀")

else:

print("挺棒")

3、in

判断是否在其中,比如是否在列表中

2 in [1,2,3,4]

4、del

delete 删除一个变量,或者删除列表中某个元素

a = "hello, world!"

b = hello

del b

print(a) # hello, world!

list = [1, 2, 3, 4, 5, 6]

del list[1]

print(list) # [1, 3, 4, 5, 6]

5、for \ while 和break \ continue

构造循环语句

continue继续,即跳过循环,立即执行下一次循环

break 退出循环语句

for i in [1,2,3,4,5,6]:

if i == 2:

continue

if i == 4:

break

print(i) # 1 3 这里跳过了i==2,并且在i==4的时候结束了循环

6、and or 和not

与或非

and与 有一个False,结果为False

or 或 只有一个False,结果为True

not非

7、def return 和yield

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

yield生成器,当函数中用了yield,解释器会把函数解释为生成器

# def return 应用

def feb(max):

a, b = 1, 1

while a < max:

yield a

a, b = b, a + b

for i in feb(20):

print(i) # 生成器写一个斐波那契数列

# yield 应用

def foo():

print("hello world!")

return

def square(num):

return num*num

foo() # hello world!

print(square(5)) # 25

8、class 定义类

面向对象的程序设计

class Cat:

def __init__(self, name):

self.__name = name

def miaow(self):

print(self.__name + " is miaow....")

cat = Cat("tom")

cat.miaow()

9、from , import 和as

from … import … as …

从 。。。导入。。。指定别名为。。。

10、assert

计算一个布尔值,断言成立,程序继续执行,断言失败,停止执行,打印出AssertError 以及指定的字符串

多用于调试, 注意不能用来替代if判断语句

x = 24

assert x % 2 == 1, "ok"

Traceback (most recent call last):

File "C:********/study.py", line 2, in assert x % 2 == 1, "ok"

AssertionError: ok

11、is

判断变量是否引用同一对象

判断对象id是否相同

12、pass

空语句,用于占位符,保持程序完整

x = 10

if x > 8:

print("ok")

else:

pass

13、None

None表示变量是控制

14、try , except 和finally

try用于捕获异常,出现异常的时候 执行except后面的语句,没有异常就执行else后面的语句

无论是否出现异常都是执行finally后面的语句

x = 2

try:

print("Let's try 0 / 0")

x = x / 0

except:

print("one exception")

else:

print("no exception")

finally:

print("this sentence must be read")

15、with和as

当with语句进入时,会执行对象的__enter__()方法,该方法返回的值会赋值给as指定的目标;当with语句退出时,会执行对象的__exit__()方法,无论是否发生异常,都会进行清理工作。

16、global

定义并通知python后面的变量是全局变量,不要定义一个新的局部变量

x = 6

def local_x():

x = 7

print("x in func = " + str(x))

local_x() # x in func = 7

print("global x = " + str(x)) # global x = 6

print("")

def global_x():

global x # 定义x是全局变量

x = 7

print("x in func = " + str(x))

global_x() # x in func = 7

print("global x = " + str(x)) # global x = 7

17、lambda

定义表达式,匿名函数

a = lambda x,y: x+y

print(a(1,2)) # 3

18、async 和 await

参考廖雪峰老师的解释:

可以把一个generator标记为coroutine类型,然后在coroutine内部用yield from调用另一个coroutine实现异步操作。

为了简化并更好地标识异步IO,从Python 3.5开始引入了新的语法async和await,可以让coroutine的代码更简洁易读。

请注意,async和await是针对coroutine的新语法,要使用新的语法,只需要做两步简单的替换:

把@asyncio.coroutine替换为async;

把yield from替换为await。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值