如何在异常处理中解决打印语句{block}除外?

时间:2019-05-23 13:54:40

标签: python

这里的问题出在异常处理中,我使用一个[list]并使用for循环迭代该列表。现在,在for循环中有一个try and catch块,其中在try块中,我将1除以列表element(r = 1/int(entry)),但是在列表中,我们有多种数据类型,例如字符串,int等。现在的问题是,当可整除成功完成时,我要打印此打印件(“的倒数”,条目,“是”,r)

import sys

lst = [2, 'b' ,0]

for entry in lst:
    try:
        print("the entry is ", entry)
        r = 1/int(entry)
    except:            
        print("oop!", sys.exc_info()[0],"occured")
        print("Next entry.")
        print("**************************")
        if(r == True):
            print("the reciprocal of", entry ,"is",r)

1 个答案:

答案 0 :(得分:1)

import sys

lst = [2, 'b' ,0]

for entry in lst:
    try:
        print("the entry is ", entry)
        r = 1/int(entry)
        print("the reciprocal of", entry ,"is",r)
    except:            
        print("oop!", sys.exc_info()[0],"occured")
        print("Next entry.")
        print("**************************")