python-错误和异常-常见错误

1.无效语法

#coding=utf-8;
a=“python”;
print a;

运行结果:

    a=“python”;
      ^
SyntaxError: invalid syntax

分析:“”使用的是中文格式。

2.ZeroDivisionError

def test(a, b):
    print(a/b)
if __name__ == '__main__':
    test(10, 5)
    test(10, 0)

运行结果:

    print(a/b)
ZeroDivisionError: integer division or modulo by zero

分析:0不能作为被除数。

3.UnboundLocalError

def test(a, b):
    if a > 5:
        c = 10
    print(b / c)
if __name__ == '__main__':
    test(6, 3)
    test(3, 2)

运行结果:

    print(b / c)
UnboundLocalError: local variable 'c' referenced before assignment

分析:3小于5,导致b/c出错

4.TypeError

def test(a, b):
    print(a+b)
if __name__ == '__main__':
    test(1, 3)
    test('1', 3)

运行结果:

    print(a+b)
TypeError: cannot concatenate 'str' and 'int' objects

分析:'1'和3的类型不一样。

 

posted @ 2022-11-14 17:25  家乐福的搬砖日常  阅读(69)  评论(0编辑  收藏  举报