看完前面几篇文章,相信大家都对python有了一定的了解,相信大家也练习写了一些代码,那么大家写代码的时候总会出现各种各样的错误,那么现在就看看我遇到的一些错误和解决方法。
1.语法错误:
错误语句:count = 1
while True:
count+=1
if count ==20:
return
错误代码:SyntaxError:'return' outside function
错误原因:return不能再方法以外使用
错误解决办法:将return放在方法体里面
2.语法错误:
错误语句:
name = '小王'
if name == '小王'
print('hello')
错误代码:SyntaxError:invalid syntax
错误原因:语法错误,非法的语法
错误解决办法:看报错的行数,从报错的那一行往上找错误
3.类型错误:
name = '小王'
age = 16
print('我的名字是'+name+'我的年龄是'+age)
错误代码:Typeerror:must be str,not int
错误原因:使用加号拼接的时候,必须使用字符串
错误解决办法:将数字转化为字符串
4.缩进错误:
错误语句:
name = '小王'
for index in range(10)
if name == '小王'
print('hello')
else:
print('nothing')
错误代码:IndentationError:expected an indented block
错误原因:缩进错误,此处只需要缩进
错误解决办法:使用tab键自动缩进
5.索引错误:
错误语句:
content = 'hello world'
print(content[21])
错误代码:IndexError:string index out of range
错误原因:索引错误,字符串超出范围
错误解决办法:查看字符串的长度,索引要小于长度
6.值错误:
错误语句:
content = 'hello world'
result = content.index('a')
print(result)
错误代码:ValueError:substring not found
错误原因:值错误,子字符串未找到
错误解决办法:仔细查找或者使用index方法
7.索引错误:
错误语句:
list1=['outMan','小李子','诺澜','皮克斯']
print(list1[5])
错误代码:IndexError:list index out of range
错误原因:索引错误,列表索引超出范围
错误解决办法:查看列表的长度,索引要小于长度
8.属性错误:
错误语句:
tp1.remove(1)
print(tp1)
错误代码:AttributeError:'tuple' object has no attribute 'remove'
错误原因:属性错误,tuple对象没有属性remove
9.类型错误:
错误语句:
dic1['fond']='学习'
dic1.pop()
print(dic1)
错误代码:TypeError:pop expected at least 1 arguments,got 0
错误原因:类型错误,pop期望得到至少一个值,但是现在参数为0
错误解决办法:给pop一个参数