源码网商城,靠谱的源码在线交易网站 我的订单 购物车 帮助

源码网商城

Python循环语句中else的用法总结

  • 时间:2020-10-27 04:34 编辑: 来源: 阅读:
  • 扫一扫,手机访问
摘要:Python循环语句中else的用法总结
[b]前言[/b] 本文讨论Python的[code]for…else[/code]和[code]while…else[/code]等语法,这些是Python中最不常用、最为误解的语法特性之一。 Python中的[code]for[/code]、[code]while[/code]等循环都有一个可选的[code]else[/code]分支(类似[code]if[/code]语句和[code]try[/code]语句那样),在循环迭代正常完成之后执行。换句话说,如果我们不是以除正常方式以外的其他任意方式退出循环,那么[code]else[/code]分支将被执行。也就是在循环体内没有[code]break[/code]语句、没有[code]return[/code]语句,或者没有异常出现。 下面我们来看看详细的使用实例。 [b]一、 常规的 if else 用法[/b]
x = True
if x:
 print 'x is true'
else:
 print 'x is not true'
[b]二、if else 快捷用法[/b] 这里的[code] if else [/code]可以作为三元操作符使用。
mark = 40
is_pass = True if mark >= 50 else False
print "Pass? " + str(is_pass)
[b]三、与 for 关键字一起用[/b] 在满足以下情况的时候,[code]else [/code]下的代码块会被执行:      1、[code]for [/code]循环里的语句执行完成      2、[code]for [/code]循环里的语句没有被 [code]break [/code]语句打断
# 打印 `For loop completed the execution`
for i in range(10):
 print i
else:
 print 'For loop completed the execution'
# 不打印 `For loop completed the execution`
for i in range(10):
 print i
 if i == 5:
 break
else:
 print 'For loop completed the execution'
[b]四、与 while 关键字一起用[/b] 和上面类似,在满足以下情况的时候,[code]else [/code]下的代码块会被执行:      1、[code]while [/code]循环里的语句执行完成      2、[code]while [/code]循环里的语句没有被 [code]break [/code]语句打断
# 打印 `While loop execution completed`
a = 0
loop = 0
while a <= 10:
 print a
 loop += 1
 a += 1
else:
 print "While loop execution completed"
# 不打印 `While loop execution completed`
a = 50
loop = 0
while a > 10:
 print a
 if loop == 5:
 break
 a += 1
 loop += 1
else:
 print "While loop execution completed"
[b]五、与 try except 一起用[/b] 和 [code]try except[/code] 一起使用时,如果不抛出异常,[code]else[/code]里的语句就能被执行。
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()
[b]总结[/b] 关于Python中循环语句中else的用法总结到这就基本结束了,这篇文章对于大家学习或者使用Python还是具有一定的参考借鉴价值的,希望对大家能有所帮助,如果有疑问大家可以留言交流。
  • 全部评论(0)
联系客服
客服电话:
400-000-3129
微信版

扫一扫进微信版
返回顶部