python 示例_Python中带有示例的关键字除外
python 示例
Python關鍵字除外 (Python except keyword)
except is a keyword (case-sensitive) in python, it is used with try... except statement to handle the exception.
除了是python中的一個關鍵字(區分大小寫),它與try ... except語句一起使用來處理異常。
except keyword defines a block which executes if statements are written in try block raise an error.
else關鍵字定義了一個塊,如果在try塊中編寫了語句,該塊將執行,并引發錯誤。
Note: We can define multiple blocks with except keyword to handle the different types of expectations by mentioning the error/exception names.
注意:我們可以通過提及錯誤/異常名稱,使用except關鍵字定義多個塊以處理不同類型的期望。
Syntax of except keyword
關鍵字除外的語法
try:statement(s)-1except:statement(s)-2While executing the statement(s)-1, if there is any exception raises, control jumps to except block and statement(s)-2 executes.
在執行語句-1時 ,如果引發任何異常,則控制跳轉到塊和語句2 除外 。
Syntax of except keyword with multiple except blocks
具有多個except塊的except關鍵字的語法
try:statement(s)-1except Error_Name1:statement(s)-Aexcept Error_Name2:statement(s)-Bexcept Error_Name3:statement(s)-C..except:statement(s)-defaultWhile executing the statement(s)-1 if Error_Name1 generates, statements written in Except Error_Name1 (statements(s)-A) executes, and so on... If any error is not mentioned with except block then last except block without any error name executes.
如果Error_Name1生成,則在執行語句-1時,將執行用Error_Name1 以外的語句編寫的語句( 語句-A ),依此類推...如果未提及任何錯誤,則除了block 以外,最后一個exception 都沒有錯誤名稱執行。
Example:
例:
Input:a = 10b = 0try:# no errorresult = a%bprint(result)except:print("There is an error")Output:There is an errorPython的除外關鍵字示例 (Python examples of except keyword)
Example 1: Find modulus of two number and handle exception, if divisor is 0.
示例1:如果除數為0,則求兩個數的模數并處理異常。
# python code to demonstrate example of # except keyword # Find modulus of two number and # handle exception, if divisor is 0a = 10 b = 3try:# no errorresult = a%bprint(result)# assign 0 to b# an error will occurb = 0result = a%bprint(result)except:print("There is an error")Output
輸出量
1 There is an errorExample 2: Write an example to handle multiple errors.
示例2:編寫示例以處理多個錯誤。
# python code to demonstrate example of # except keyword # Write an example to handle multiple errorsa = 10 b = 3try:# del b # uncomment this to test NameError# no errorresult = a%bprint(result)# assign 0 to b# an error will occurb = 0result = a%bprint(result)except ZeroDivisionError:print("Can not divide by 0") except NameError:print("A NameError in the code") except:print("There is an error")Output
輸出量
1 Can not divide by 0翻譯自: https://www.includehelp.com/python/except-keyword-with-example.aspx
python 示例
總結
以上是生活随笔為你收集整理的python 示例_Python中带有示例的关键字除外的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 摩尔庄园怎么扩建家园农场
- 下一篇: 3000元左右的家用家用投影仪哪个好用,