python 示例_Python中带有示例的关键字除外
python 示例
Python關(guān)鍵字除外 (Python except keyword)
except is a keyword (case-sensitive) in python, it is used with try... except statement to handle the exception.
除了是python中的一個(gè)關(guān)鍵字(區(qū)分大小寫),它與try ... except語(yǔ)句一起使用來(lái)處理異常。
except keyword defines a block which executes if statements are written in try block raise an error.
else關(guān)鍵字定義了一個(gè)塊,如果在try塊中編寫了語(yǔ)句,該塊將執(zhí)行,并引發(fā)錯(cuò)誤。
Note: We can define multiple blocks with except keyword to handle the different types of expectations by mentioning the error/exception names.
注意:我們可以通過(guò)提及錯(cuò)誤/異常名稱,使用except關(guān)鍵字定義多個(gè)塊以處理不同類型的期望。
Syntax of except keyword
關(guān)鍵字除外的語(yǔ)法
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.
在執(zhí)行語(yǔ)句-1時(shí) ,如果引發(fā)任何異常,則控制跳轉(zhuǎn)到塊和語(yǔ)句2 除外 。
Syntax of except keyword with multiple except blocks
具有多個(gè)except塊的except關(guān)鍵字的語(yǔ)法
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生成,則在執(zhí)行語(yǔ)句-1時(shí),將執(zhí)行用Error_Name1 以外的語(yǔ)句編寫的語(yǔ)句( 語(yǔ)句-A ),依此類推...如果未提及任何錯(cuò)誤,則除了block 以外,最后一個(gè)exception 都沒(méi)有錯(cuò)誤名稱執(zhí)行。
Example:
例:
Input:a = 10b = 0try:# no errorresult = a%bprint(result)except:print("There is an error")Output:There is an errorPython的除外關(guān)鍵字示例 (Python examples of except keyword)
Example 1: Find modulus of two number and handle exception, if divisor is 0.
示例1:如果除數(shù)為0,則求兩個(gè)數(shù)的模數(shù)并處理異常。
# 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:編寫示例以處理多個(gè)錯(cuò)誤。
# 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 示例
總結(jié)
以上是生活随笔為你收集整理的python 示例_Python中带有示例的关键字除外的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 摩尔庄园怎么扩建家园农场
- 下一篇: python中dict函数_dict()