用法:如果 if 条件满足,则执行 if 语句块,否则执行 else 语句块。
if(True):
print('i love you')
else:
print('i dont love you')
用法:当while/for循环顺利完成 即没有break跳出 才会执行else语句块。
例:验证是否是素数,如果不是素数,求最大公约数:
def showMaxFactor(num):
count = num // 2 #地板除法
while count>1:
if num%count == 0:
print('%d最大的约数是%d'%(num,count))
break
count-=1
else:
print('%d是素数'%num)
num=int(input('请输入一个整数!'))
showMaxFactor(num)
用法:只要try语句没有任何异常,顺利完成,才会执行else语句块。
try:
int('123')
#int('bc')
except ValueError as reason:
print('出错啦!'+str(reason))
else:
print('没有任何异常!')
如果采用上阶段的try - finally 关闭文件,有可能会出现这么一种情况:
文件根本不存在,却要关闭,则会出错:
try:
f=open('D:\\data.txt','r')
for eachline in f:
print(eachline)
except OSError as reason:
print('出错啦!' + str(reason))
finally:
f.close()
try:
f=open('D:\\dataaaa.txt','r')
for eachline in f:
print(eachline)
except OSError as reason:
print('出错啦!' + str(reason))
finally:
try:
f.close()
except NameError as reason:
print('出错啦!' + str(reason))
try:
with open('D:\\data.txt','r') as f:
for eachline in f:
print(eachline)
except OSError as reason:
print('出错啦!' + str(reason))