Python pass语句–通过Python
时间:2020-02-23 14:43:08 来源:igfitidea点击:
亲爱的学习者,一切进展如何?希望您学习愉快。
在上一教程中,我们了解了Python break and continue语句以控制python循环。
您可以在这里找到该教程。
在本教程中,我们将学习Python pass语句。
Python pass语句
您可以将python pass语句视为无操作语句。
Python注释和pass语句之间的区别是;在解释程序时,注释将被消除,但pass语句则不会。
它像有效语句一样消耗执行周期。
例如,仅打印列表中的奇数,我们的程序流程将是:
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。
因此,您需要做的是像这样将pass语句添加到每个未实现的函数中。
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 pass语句?实际上,似乎在我们之前的示例中,如果仅注释掉未实现的功能(如下所示),我们仍将获得所需的输出。
#def func1(): # TODO: implement func1 later #def func2(): # TODO: implement func2 later def func3(a): print (a) func3("Hello")
但是,如果您一次处理一个庞大的python项目,则可能需要诸如pass语句之类的东西。
这就是为什么在Python中引入pass语句的原因。