相信很多小伙伴在日常敲代码的过程中,一不小心或者一不留神就会出错,程序总会被各种各样的bug困住,扰乱我们这些程序猿的心境。那么今天我就来跟大家分享一下简单常见的BUG及相应BUG的处理方法,这样的话,下次我们再遇到这些BUG,就能很轻松解决掉,程序得以运行。

错误一:

# TypeError: cannot concatenate 'str' and 'int' objects  
    # 不能连接str和int对象  
    age = 18  
    str = "我今年" + age + "喜欢音乐"  
    # 分析:  
    # 这是一个类型错误,意味着Python无法识别你使用的信息。在这个示例中,Python发现你使  
    # 用了一个值为整数( int )的变量,但它不知道该如何解读这个值。Python知道,这个变  
    # 量表示的可能是数值18,也可能是字符1和8。像上面这样在字符串中使用整数时,需要显式地指  
    # 出你希望Python将这个整数用作字符串。为此,可调用函数 str() ,  
    # 它让Python将非字符串值表示为字符串:  
    #解决方法: str = "我今年 " + str(age) + "喜欢音乐"  
    print(str);</code>

错误二:

# IndexError: list index out of range
# 索引错误:列表索引超出范围
# Python试图向你提供位于索引3处的元素,但它搜索列表 name 时,却发现索引3处没有元素
# 鉴于列表索引差一的特征,这种错误很常见。有些人从1开始数,因此以为第三个元素的
# 索引为3;但在Python中,因为索引是从0开始的,所以第三个元素的索引为2。
name = ['tom', 'rose', 'lilei'];
print(name[3])

错误三:

# IndentationError: expected an indented block
# 缩进错误:预期一个缩进快(意思需要一个缩进块)
str1 = ['tom', 'rose', 'lilei'];
for name in str1:
print(name);

错误四:

# IndentationError: unexpected indent
# 缩进错误:意外缩进(这里不应缩进)
str2 = "Hello world!";
	print(str2);

错误五:

# TypeError: 'tuple' object does not support item assignment
    dimensions = (200,50);
    print(dimensions);
    print(dimensions[0]);
    print(dimensions[1]);
    # TypeError: 'tuple' object does not support item assignment
    # 类型错误:元组对象不支持元素值重新分配,也就是不能尝试去修改元组中的任一个元素的值
    # dimensions[0] = 250;
    print(dimensions);

错误六:

# SyntaxError: invalid syntax
    # 语法错误 非法的语法
    # 解决办法:看报错信息在第几行 ,从这一行往上找错误
    # if name == '小王'
    #     print('Hello')

    tp1 = ()
    tp2 = tuple()
     
    tp1 = ((),[],{},1,2,3,'a','b','c',3.14 ,True)
    print(tp1[:])
    print(tp1[1:: 2])
    print(tp1[5])
    # AttributeError: 'tuple' object has no attribute 'remove'
    # attribute 属性 object对象

错误七:

属性错误:元组对象没有属性'remove'
    tp1.remove(1)
    print(tp1)



    dic1 = {
        'name': '张三',
        'age' : 17 ,
        'friend':['李四','王五','赵六','冯七']
    }
    # 获取指定key值对应的name值
    print(dic1['name'])
    # KeyError: 'fond'

错误八:

# key 键错误 没有指定的键值“fond”
# print(dic1['fond'])

   八个错误虽然全部错误没有写出来,但是如果掌握这八个,在日常的代码过程中,能帮我们解决很多不必要的困扰,希望大家可以好好看一下。

未完待续.....