亲爱的学习者,一切进展如何?希望你学得好。在上一个教程中,我们学习了控制Python循环的Python break and continue语句。你可以找到那个教程在这里. 在本教程中,我们将学习Python pass语句。
Python pass语句
可以将python pass语句视为no operation语句。Python注释和通过语句是;注释在解释程序时被删除,但是通过语句没有。它像有效语句一样消耗执行周期。例如,对于只打印列表中的奇数,我们的程序流程将是:
List <- a list of number
for each number in the list:
if the number is even,
then, do nothing
else
print odd number
现在如果我们把上面的东西转换成python,
#Generate a list of number
numbers = [ 1, 2, 4, 3, 6, 5, 7, 10, 9 ]
#Check for each number that belongs to the list
for number in numbers:
#check if the number is even
if number % 2 == 0:
#if even, then pass ( No operation )
pass
else:
#print the odd numbers
print (number),
输出将是
>>>
================== RESTART: /home/imtiaz/Desktop/pass1.py ==================
1 3 5 7 9
>>>
假设您需要逐个实现多个函数。但是在实现函数之后,必须检查每个函数。如果你留下这样的东西:
def func1():
# TODO: implement func1 later
def func2():
# TODO: implement func2 later
def func3(a):
print (a)
func3("Hello")
然后,您将得到IndentationError。
所以,你需要做的是,增加通行证语句对每个没有实现的函数都是这样。
def func1():
pass # TODO: implement func1 later
def func2():
pass # TODO: implement func2 later
def func3(a):
print (a)
func3("Hello")
对于上面的代码,您将得到如下输出
================== RESTART: /home/imtiaz/Desktop/pass3.py ==================
Hello
>>>
为什么要使用Python pass语句
现在,您可能会想到一个问题,为什么要使用Python通过声明?实际上,在前面的例子中,如果我们只是注释掉未实现的函数,如下面所示,我们仍然可以得到我们想要的输出。
#def func1():
# TODO: implement func1 later
#def func2():
# TODO: implement func2 later
def func3(a):
print (a)
func3("Hello")
但是,如果您在一个大型python项目中工作,您可能需要类似pass语句的东西。这就是为什么在Python中引入pass语句。
今天到此为止。希望您能很好地学习Python pass语句。请继续关注我们的下一个教程,如果有任何困惑,请随时使用评论框。
参考文献:官方文件