Python中else语句整理
来源:互联网 发布:房地产的软件 编辑:程序博客网 时间:2024/05/16 16:23
if-else语句:
和各种语言相同的用法,在条件语句中,与if语句搭配使用的else语句。如果if语句的条件表达式的结果布尔值为假,那么程序将执行else语句后的代码。它的语法是大家最为熟知的:
if expression:
expr_true_suite
else:
expr_false_suite
elif是python提供的else-if语句,它检查多个条件表达式的值是否为真,并在为真时执行特定代码块中的代码。和else一样,elif是可选的,但是要注意的是,一个if语句可以跟多个elif语句,但最后只能有一个else语句:
if expression1:
expr1_true_suite
elif expression2:
expr2_true_suite
elif expressionN:
exprN_true_suite
else:
none_of_the_above_suite
在其他语言中,除了条件语句,是不会见到else分支的,但在Python中,while和for循环中,也是可以使用else语句的。它们的工作 顺序为:在循环中使用时,else语句只在循环完成后执行,也就是说,break语句也会跳过else代码块,只要循环是正常结束,而不是通过 break,else语句就会执行。
while-else举例:
#!/usr/bin/env python
# 寻找最大约数
def showMaxFactor(num):
count=num/2
while count>1:
if num%count == 0:
print 'largest factor of %d is %d' % (num,count)
break
count -=1
else:
print num,'is prime'
for i in range(10,21):
showMaxFactor(i)
程序的执行结果为:
largest factor of 10 is 5
11 is prime
largest factor of 12 is 6
13 is prime
largest factor of 14 is 7
largest factor of 15 is 5
largest factor of 16 is 8
17 is prime
largest factor of 18 is 9
19 is prime
largest factor of 20 is 10
try-else语句:对于python中的错误和异常,try-except语句段,也可以和else连用,其功能和循环中的else语句没有多大区别:在try范围内没有检测到异常的时候,执行else子句。看一下语法:
try:
log = open('logfile.txt','w')
except:
print 'file logfile.txt is not exsit'
else:
log.write('no exception caught')
log.close()
当然,在异常处理中,else一样可以和finally联用:try-except-else-finally。
- Python中else语句整理
- Python中else语句整理
- Python中else语句整理
- python中else语句的用法
- Python中循环语句中的else用法
- Python 中 else语句的其他用法
- Python 中的else语句
- Python else语句
- Python中if-else语句的多种写法
- Python中if-else语句的多种写法
- Python中if-else语句的多种写法
- Python中if-else语句的多种写法
- python else在for、while、try 语句中使用
- Python try-except-else 语句
- Python循环中的else语句
- python学习:for else语句
- Python if elif else语句
- 3.1 Python if else语句
- ArcGIS应用Oracle Spatial特征分析
- hadoop 倒排索引
- 进度条的使用
- python异常except语句用法与引发异常
- 路由算法
- Python中else语句整理
- android 高级组件之 AutoCompleteTextView
- banner
- Derby数据库
- 如何判断一个静态库(.a文件)所支持的架构(平台)
- AlertDialog
- SQL 表合并,内连,左连,右连
- 只可以初始化一次的类实例
- 中移动董事长王建宙:数据及物联网将成未来增长点