Python 入门简明教程
1. 1. 与 Python 的第一次亲密接触-写给初学者 2. 2. Python 语法关键字 3. 3. Python 的注释和语法 4. 4. Python 基本数据类型 5. 5. Python 输入输出 6. 6. Python 运算符 7. 7. Python 变量 8. 8. Python 命名空间和变量生存范围 9. 9. Python 逻辑判断 10. 10. Python For 循环语法 11. 11. Python While 循环语法 12. 12. Python 循环语法中 break 与 continue的使用 13. 14. Python 三目运算符 14. 15. Python 循环语法中 pass 语句的使用 15. 16. Python 循环语法示例 16. 17. Python 函数 17. 18. Python main 函数 18. 19. Python print 函数 19. 20. Python print format 输出格式化 20. 21. Python print 输出到文件 21. 22. Python 输入 22. 23. Python import 导入模块 23. 25. Python 中递归的使用 24. 26. Python 匿名函数 25. 27. Python lambda 26. 28. Python PIP 包管理机制 27. 29. Python 命令行参数 28. 30. Python Numbers 包 29. 31. Python 随机数 30. 32. Python String 转 int 31. 34. Python 自定义异常 Exception 32. 35. Python 继承 33. 36. Python 父类 34. 38. Python 操作符重载 35. 39. Python __str__ and __repr__

15. Python 循环语法中 pass 语句的使用

亲爱的学习者,一切进展如何?希望你学得好。在上一个教程中,我们学习了控制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语句。请继续关注我们的下一个教程,如果有任何困惑,请随时使用评论框。

参考文献:官方文件