Python-关键字-0.不常用关键字汇总

yield

Yield 语句暂停函数的执行并将一个值发送回调用者,但保留足够的状态以使函数能够从中断处恢复。当函数恢复时,它会在上次yield 运行后立即继续执行。这使得它的代码随着时间的推移产生一系列值,而不是立即计算它们并像列表一样将它们发送回来。

1
2
3
4
5
6
7
8
9
10
11
12
13

# A Simple Python program to demonstrate working of yield
# A generator function that yields 1 for the first time,
# 2 second time and 3 third time

def simpleGeneratorFun():
yield 1
yield 2
yield 3

# Driver code to check above generator function
for value in simpleGeneratorFun():
print(value)

1
2
3
1
2
3

assert

验证某个条件是否成立,不成立就退出任务。

1
2
3
4
5
6
7
8
x = "hello"

#if condition returns True, then nothing happens:
assert x == "hello"

x = "welcome"
#if condition returns False, AssertionError is raised:
assert x != "hello", "x should be 'hello'"

nolocal

1
2
3
4
5
6
7
8
def myfunc1():
x = "John"
def myfunc2():
x = "hello"
myfunc2()
return x

print(myfunc1())
-------------本文结束感谢您的阅读-------------