除了块之外的打印语句

问题描述 投票:0回答:1
import sys
lst = ['b', 0, 2,5]
for entry in lst:
  try:
    print("****************************")
    print("The entry is", entry)
    r = 1 / int(entry)
  except(ValueError):
    print("This is a ValueError.")
  except(ZeroDivisionError):
    print("This is a ZeroError.")
  except:
    print("Some other error")
print("The reciprocal of", entry, "is", r)

当程序将输入作为2时,除块外的打印语句将被跳过。但是,如果我在列表中仅给出3个元素,它将正常工作。

python try-except
1个回答
0
投票

这是因为print语句在for循环之外。因此,它仅打印entry的最后一次迭代。

检查此:

In [1340]: import sys 
      ...: lst = ['b'] 
      ...: for entry in lst: 
      ...:   try: 
      ...:     print("****************************") 
      ...:     print("The entry is", entry) 
      ...:     r = 1 / int(entry) 
      ...:   except(ValueError): 
      ...:     print("This is a ValueError.") 
      ...:   except(ZeroDivisionError): 
      ...:     print("This is a ZeroError.") 
      ...:   except: 
      ...:     print("Some other error") 
      ...: print("The reciprocal of", entry, "is", r)
****************************
The entry is b
This is a ValueError.
The reciprocal of b is 0.2
© www.soinside.com 2019 - 2024. All rights reserved.