Python中的10个常见错误函数使用案例
发布时间:2023-07-29 20:26:51
Python中的10个常见错误函数使用案例:
1. IndexError:下标越界错误
示例:
nums = [1, 2, 3] print(nums[3]) # IndexError: list index out of range
2. KeyError:字典键错误
示例:
d = {'a': 1, 'b': 2}
print(d['c']) # KeyError: 'c'
3. TypeError:类型错误
示例:
num = '1' print(num + 2) # TypeError: can only concatenate str (not "int") to str
4. ValueError:数值错误
示例:
int('a') # ValueError: invalid literal for int() with base 10: 'a'
5. ImportError:导入错误
示例:
import non_existent_module # ImportError: No module named 'non_existent_module'
6. AttributeError:属性错误
示例:
s = 'hello'
print(s.append('!')) # AttributeError: 'str' object has no attribute 'append'
7. FileNotFoundError:文件不存在错误
示例:
file = open('non_existent_file.txt') # FileNotFoundError: No such file or directory: 'non_existent_file.txt'
8. ZeroDivisionError:除零错误
示例:
x = 10 y = 0 print(x/y) # ZeroDivisionError: division by zero
9. SyntaxError:语法错误
示例:
print 'hello' # SyntaxError: Missing parentheses in call to 'print'. Did you mean print('hello')?
10. IndentationError:缩进错误
示例:
def func():
print('hi') # IndentationError: expected an indented block
以上是Python中常见的10个错误函数使用案例,开发人员在编写代码时应尽量避免这些错误,通过适当的异常处理机制来处理这些错误,提高代码的可靠性和稳定性。
