ValueError和TypeError

ValueError: Occurs when a built_in operation or function is given an argument with the correct type but an innappropriate value.

TypeError: Raised when an operation or function is applied to an object of inappropriate type.

This exception may be raised by user code to indicate that an attempted operation on an object is not supported, and is not meant to be. If an object is meant to support a given operation but has not yet provided an implementation, NotImplementedError is the proper exception to raise.

Passing arguments of the wrong type (e.g. passing a list when an int is expected) should result in a TypeError, but passing arguments with the wrong value (e.g. a number outside expected boundaries) should result in a ValueError.

代码示例:

代码1:


x = int(input('Enter a number:'))

x += 20

print(x)

Enter a number:[1]

运行结果:

ValueError                                Traceback (most recent call last)
 in ()
----> 1 x = int(input('Enter a number:'))
      2 x += 20
      3 print(x)

ValueError: invalid literal for int() with base 10: '[1]'

代码2:


x = str(input('Enter a number:'))

x += 20

print(x)

Enter a number:10
运行结果:

TypeError                                 Traceback (most recent call last)
 in ()
      1 x = str(input('Enter a number:'))
----> 2 x += 20
      3 print(x)

TypeError: must be str, not int

简单的理解为当需要内置运算符或函数来进行操作时如‘2’+2,会出现TypeError。
当只存在于运算符的一侧时,不涉及内置运算符或函数的运算,如代码1所示,会被认定为ValueError。

你可能感兴趣的:(ValueError和TypeError)