例外處理 try: ... excpet:
a=100
b=10
try:
c=a/b
print("c=",c)
except:
c=-1
print("Divdie by zero")
print("c=",c)
print("c=",c)
------------------
try-except 也可以和 else 連用, else 後的程式區塊放的是沒有發生例外,程式所執行的工作,例如
try:
c=a/b
print("c=",c)
except:
c=-1
print("Divdie by zero")
print("c=",c)
else:
print("No exception")
-----------------------------------------------
例外的名稱也可以寫在 except 之後,如
try:
c=a/b
print("c=",c)
except ZeroDivisionError:
c=-1
print("Divdie by zero")
print("c=",c)
except NameError:
except TypeError:
except IndexError:
-----------------------------
若加入另一個關鍵字 finally ,無論例外有沒有發生都會執行 finally 後的程式區塊
try:
c=a/b
print("c=",c)
except ZeroDivisionError:
c=-1
print("Divdie by zero")
print("c=",c)
except NameError:
except TypeError:
except IndexError:
findally:
--------------------------
Raise 觸發Exception Error
try:
raise NameError
except NameError:
print("發生例外,NameError")
except ZeroDivisionError:
print("發生例外,ZeroDivisionError")
print("after exception....")
Python 所有Exception
https://docs.python.org/3/library/exceptions.html#exception-hierarchy
file = open('dream.txt', 'r', encoding='UTF-8')
li=file.readlines()
print(li[3],end='')
https://pypi.python.org/pypi?:action=browse&c=533&show=all
安裝 Python 第三方套件-使用pip 工具
C:\Python34\Scripts>pip install pyqrcode
Collecting pyqrcode
Downloading PyQRCode-1.1.tar.gz
Building wheels for collected packages: pyqrcode
Running setup.py bdist_wheel for pyqrcode
Stored in directory: C:\Users\student\AppData\Local\pip\Cache\wheels\03\93\7f\
d3a38165d01798524d99329a6aabba2b378d81da1d46f15b36
Successfully built pyqrcode
Installing collected packages: pyqrcode
Successfully installed pyqrcode-1.1
C:\Python34\Scripts>pip install pypng
#-*-coding:UTF-8 -*-
# EX08_01.py
#
# pyqrcode 使用範例
#
from pyqrcode import QRCode
url = QRCode('http://www.ntu.edu.tw')
#輸出SVG格式檔案:url.svg ,縮放比為10
url.svg('url.svg', scale=10)
#輸出PNG格式檔案:url.png ,縮放比為10
url.png('url.png', scale=10)
https://docs.python.org/3/library/exceptions.html#exception-hierarchy
Python檔案處理
file = open('dream.txt', 'r', encoding='UTF-8')
li=file.readlines()
print(li[3],end='')
Python 第三方套件
https://pypi.python.org/pypi?:action=browse&c=533&show=all
安裝 Python 第三方套件-使用pip 工具
C:\Python34\Scripts>pip install pyqrcode
Collecting pyqrcode
Downloading PyQRCode-1.1.tar.gz
Building wheels for collected packages: pyqrcode
Running setup.py bdist_wheel for pyqrcode
Stored in directory: C:\Users\student\AppData\Local\pip\Cache\wheels\03\93\7f\
d3a38165d01798524d99329a6aabba2b378d81da1d46f15b36
Successfully built pyqrcode
Installing collected packages: pyqrcode
Successfully installed pyqrcode-1.1
C:\Python34\Scripts>pip install pypng
#-*-coding:UTF-8 -*-
# EX08_01.py
#
# pyqrcode 使用範例
#
from pyqrcode import QRCode
url = QRCode('http://www.ntu.edu.tw')
#輸出SVG格式檔案:url.svg ,縮放比為10
url.svg('url.svg', scale=10)
#輸出PNG格式檔案:url.png ,縮放比為10
url.png('url.png', scale=10)
沒有留言 :
張貼留言