在我们学习python的过程中难免会碰到很多bug,因此,我们要想学好python,就必须先解决这些bug,遇到每一个bug的时候能在第一时间想到解决问题的方法,下面是我分析的,在各种场景中下出现的各种bug及解决方法。
1.SyntaxError: invalid syntax(语法错误)
x= 0
while x <100 (少个双引号)
x +=1
if x ==4:
continue
print('x为:{}'.format(x))
2. AttributeError: 'tuple' object has no attribute 'remove'(属性错误,元组对象没有属性‘remove’)
tp1 =((),[],{},1,3,4,'',3.14,True)
print(tp1[:])
print(tp1[1::2])
print(tp1[5])
tp1.remove(1) (这里的remove不能这么用,在元组里,元素不能进行增删改)
print(tp1)
3.IndexError: list index out of range(索引错误)
list1 =['azdas','撒爱上我','abc','张三']
print(list1[10]) (10超出了索引范围,索取的元素必须在这个列表的范围内)
4..ValueError: substring not found(值错误)
list1 = ['hello world']
result = list1.index('嗨') (不能找到 ‘嗨’在列表的元素中,更不能找到其所在的索引号)
print(result)
5.ValueError: the first two maketrans arguments must have equal length(值错误)
content= "1加2的值是3"
s = str.maketrans('值','sq') (一个元素只能替换一个元素)
content = content.translate(s)
print(content)
6.TypeError: replace() takes at least 2 arguments (1 given)(类型错误)
content= "1加2的值是3"
s = str.replace('值','s') (在这里不能用replace,若用replace则需要两个参数)
content = content.translate(s)
print(content)
7.KeyError: 'fond' (键错误)
dict1={
"name":"张三",
"age":18,
"friend":['李四','王五','赵六']
}
print(dict1["name"])
# print(dict1['fond'])(因为dict1字典里没有 “name”这个键,因此会报错)
或者加一个
dict1['fond']= '吃鸡'
print(dict1)(可以加一个key与value值)
8.TypeError: pop expected at least 1 arguments, got 0(类型错误)
#dict1={
"name":"张三",
"age":18,
"friend":['李四','王五','赵六']
}
dict1.pop() (在这里pop删除键值对必须要加参数,比如删除“name”则要在pop后边的参数既小括号里添加一个参数 "")
print(dict1)
万事都是日积月累,只有不断努力,才有可能成功,加油!