遇到的Python常见错误:TypeError和ValueError解析实例
在Python编程中,TypeError
和ValueError
是两种常见的运行时错误。它们分别对应于数据类型不匹配和数据值不符合预期两种情况。
TypeError: 当你尝试对一个对象调用方法或属性,但这个对象的类型不允许这样做时,就会出现TypeError。
str_obj = "Hello"
int_obj = 42
# TypeError: 'str' object cannot be
# used with 'int''
try:
str_obj + int_obj
except TypeError as e:
print(e) # Output: 'str' object cannot be used with 'int'
ValueError: 当你尝试对一个数据进行计算或转换,但这个数据的值不符合预期要求时,就会出现ValueError。
num = input("Enter a number: ")
if not num.isdigit(): # Not a digit error
raise ValueError("Invalid input. Please enter a number.")
try:
float_num = float(num)
print("Converted to float:", float_num)
except ValueError as e:
print(e) # Output: 'Invalid input. Please enter a number.'
以上就是Python中TypeError
和ValueError
的常见错误解析实例。
还没有评论,来说两句吧...