Python循环语句中else的用法总结
2016-09-11 17:03
851 查看
本文讨论Python的
for…else和
while…else等语法,这些是Python中最不常用、最为误解的语法特性之一。
Python中的
for、
while等循环都有一个可选的
else分支(类似
if语句和
try语句那样),在循环迭代正常完成之后执行。换句话说,如果我们不是以除正常方式以外的其他任意方式退出循环,那么
else分支将被执行。也就是在循环体内没有
break语句、没有
return语句,或者没有异常出现。
下面我们来看看详细的使用实例。
一、 常规的if else用法
x = True if x: print 'x is true' else: print 'x is not true'
二、if else快捷用法
这里的
if else可以作为三元操作符使用。
mark = 40 is_pass = True if mark >= 50 elseFalse print "Pass? " + str(is_pass)
三、与 for关键字一起用
在满足以下情况的时候,
else下的代码块会被执行:
1、
for循环里的语句执行完成
2、
for循环里的语句没有被
break语句打断
# 打印 `For loop completed the execution` fori in range(10): print i else: print 'For loop completed the execution' # 不打印 `For loop completed the execution` fori in range(10): print i if i == 5: break else: print 'For loop completed the execution'
四、与 while关键字一起用
和上面类似,在满足以下情况的时候,
else下的代码块会被执行:
1、
while循环里的语句执行完成
2、
while循环里的语句没有被
break语句打断
# 打印 `While loop execution completed` a = 0 loop = 0 whilea <= 10: print a loop += 1 a += 1 else: print "While loop execution completed" # 不打印 `While loop execution completed` a = 50 loop = 0 whilea > 10: print a if loop == 5: break a += 1 loop += 1 else: print "While loop execution completed"
五、与 try except 一起用
和
try except一起使用时,如果不抛出异常,
else里的语句就能被执行。
file_name = "result.txt" try: f = open(file_name, 'r') except IOError: print 'cannot open', file_name else: # Executes only if file opened properly print file_name, 'has', len(f.readlines()), 'lines' f.close()
总结
关于Python中循环语句中else的用法总结到这就基本结束了,这篇文章对于大家学习或者使用Python还是具有一定的参考借鉴价值的,希望对大家能有所帮助,如果有疑问大家可以留言交流。
您可能感兴趣的文章:
相关文章推荐
- Python循环语句中else的用法总结
- python 循环语句的else语句用法,当循环条件变为假,切不是通过breakbreak终止的时候,就会执行这个else语句。
- Python学习笔记——print语句用法总结
- python中循环语句while用法实例
- Python的for和break循环结构中使用else语句的技巧
- Python中的if、else、elif语句用法简明讲解
- python3 for 循环中的 else 语句
- 详解Python中的循环语句的用法
- 一周stackoverflow热门问题选登:如何正确的理解python for循环中的else用法?
- Python中的条件判断语句与循环语句用法小结
- Python 小技巧:for 循环后面接 else 语句
- python中while循环语句用法简单实例
- 在Python的while循环中使用else以及循环嵌套的用法
- python中list循环语句用法实例
- [Python]循环语句中的 else 子句
- Python循环语句之break与continue的用法
- 在Python的while循环中使用else以及循环嵌套的用法
- Python 中 else语句的其他用法
- Python循环中的else语句
- Python的for和break循环结构中使用else语句的技巧