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

yipeiwu_com6年前Python基础

前言

本文讨论Python的for…elsewhile…else等语法,这些是Python中最不常用、最为误解的语法特性之一。

Python中的forwhile等循环都有一个可选的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 else False
print "Pass? " + str(is_pass)

三、与 for 关键字一起用

在满足以下情况的时候,else 下的代码块会被执行:

     1、for 循环里的语句执行完成

     2、for 循环里的语句没有被 break 语句打断

# 打印 `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'

四、与 while 关键字一起用

和上面类似,在满足以下情况的时候,else 下的代码块会被执行:

     1、while 循环里的语句执行完成

     2、while 循环里的语句没有被 break 语句打断

# 打印 `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"

五、与 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 HTTP服务

超如果你急需一个简单的Web Server,但你又不想去下载并安装那些复杂的HTTP服务程序,比如:Apache,ISS等。那么, Python 可能帮助你。使用Python可以完成一个...

python enumerate内置函数用法总结

python enumerate内置函数用法总结

这篇文章主要介绍了python enumerate内置函数用法总结,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 enumera...

python 字典操作提取key,value的方法

python 字典操作提取key,value的方法

python 字典操作提取key,value dictionaryName[key] = value 1.为字典增加一项 2.访问字典中的值 3、删除字典中的一项...

对Python强大的可变参数传递机制详解

今天模拟定义map函数.写着写着就发现Python可变长度参数的机制真是灵活而强大. 假设有一个元组t,包含n个成员: t=(arg1,...,argn) 而一个函数f恰好能接受n...

pygame游戏之旅 添加icon和bgm音效的方法

pygame游戏之旅 添加icon和bgm音效的方法

本文为大家分享了pygame游戏之旅的第14篇,供大家参考,具体内容如下 添加icon需要用的函数是: gameIcon = pygame.image.load("carIcon.p...