【问题标题】:What mistake did I make in 'TypeError'? And why does it show 'can be undefined' in the variable names in except section?我在“TypeError”中犯了什么错误?为什么它在除了部分的变量名中显示“可以未定义”?
【发布时间】:2021-11-04 16:39:51
【问题描述】:
try:
    day = int(input())
    month = int(input())

    if month == 0:
        raise ZeroDivisionError
    elif day > 31 or month > 12:
        raise ValueError
    elif type(day) != int() or type(month) != int():
        raise TypeError

except ZeroDivisionError:
    print(month, "is not a valid month")
except ValueError:
    if month > 12:
        print(month, 'is not a valid month')
    elif day > 31:
        print(day, 'is not a valid day of any month')
except TypeError:
    print("Please do not enter any string as input")

else:
    if day < 10:
        distance = 5 + (day * 2) / month
    else:
        distance = 3 + (day / month)
    print(distance, "Kilometres")

当我运行它并输入一个无效的数据类型变量时,它不会引发TypeError,而是显示ValueError。 在我的 except 部分开始的代码中,PyCharm 显示我的变量 'month''day' 未定义。 我该怎么办?

【问题讨论】:

  • 如果您输入 a 作为day 会发生什么?
  • 那是因为int("some string which isn't all digits")raise ValueError,而不是TypeError

标签: python exception typeerror valueerror


【解决方案1】:

input() 总是返回一个字符串

int() 转换将为不可解析的输入抛出 ValueError,否则,始终是 int 类型。

因此,您的 type() 检查是没有意义的(无论如何您都会使用 isinstance 来检查类型)。
如果int() 调用引发异常,则永远不会分配daymonth 中的一个或两个,因此如果没有在try 之外预先声明,则不能在异常块中使用

例如

day = None
month = None

try:
  day = int(input())
  month = int(input())
except ValueError:
  if day is not None:
    # then the error is on the month
  else:
    # error on the day

我建议定义您自己的 DateError 类以进行范围验证

【讨论】:

    猜你喜欢
    • 2017-10-12
    • 2023-03-03
    • 2016-12-09
    • 2023-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-04
    相关资源
    最近更新 更多