天天看點

Python文法基礎刻意練習:Task09(else與with語句)

else的用法

1.if—else結構

最常見的的if—else語句:

num=int(input('please input a number which is not 0: '))
if num>0:
	print('+')
else:
	print('-')
           

2.while—else

當while中有break時,可以用else判斷是否執行了break:

num=int(input('please input a number: '))
temp=num-1
while temp>1:
	if num%temp==0:
		print('num is not a prime.')
		break
	temp=temp-1
else:
	print('num is a prima.')
           

3.try—except—else

# -*- coding: UTF-8 -*-
try:
    fh = open("try3.py")
    fh.write("這是一個測試檔案,用于測試異常!!")
except IOError:
    print ("Error: 沒有找到檔案或讀取檔案失敗")
else:
    print ("内容寫入檔案成功")
    fh.close()
           

with語句

将檔案關閉的問題抽象化,不需關注細節,with 自動調用f.close(),關閉該檔案。使用了 with 語句,不管在處理檔案過程中是否發生異常,都能保證 with 語句執行完畢後已經關閉了打開的檔案句柄。

try:
    with open('try3.py','w') as f:
        for eachline in f:
            print(eachline)
except OSError as reason:
    print('出錯啦:'+ str(reason))     #出錯啦:not readable
           

繼續閱讀