我尝试调试此代码,但似乎无法正常工作

时间:2019-05-05 06:50:03

标签: python

这是Python中一个简单的异常处理问题。我已经尝试过使用map()获取输入a和b,但是我不明白为什么会出现以下错误。

我的解决方案:

for i in range(int(input())):
    a, b = map(int, input().split())
    try:
        print(a//b)
    except BaseException as e:
        print("Error Code: ", e)

输入:

3
1 0
2 $
3 1

输出:

Traceback (most recent call last):
  File "Solution.py", line 3, in <module>
    a, b = map(int, input().split())
ValueError: invalid literal for int() with base 10: '$'

1 个答案:

答案 0 :(得分:1)

>>> int('$')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: '$'

a, b = map(int, input().split())

此行尝试将输入强制转换为int,而第二行输入的$无效。您也应该尝试一下该部分,例如:

for i in range(int(input())):
    try:
        a, b = map(int, input().split())
    except Exception as e:
        print("Error Code: ", e)
        continue
    try:
        print(a//b)
    except BaseException as e:
        print("Error Code: ", e)