寫Python的時候遇到的一些常見的錯誤

1.語法錯誤

if 'b' in list1:
    print('存在')
    return
else:
    print('不存在')

SyntaxError: 'return' outside funtion

語法錯誤:return 在函數外使用

解決方法:將return放在函數中

if 'b' in list1:
    print('存在'
else:
    print('不存在')

SyntaxError:  invalid syntax

語法錯誤:非法的語法

解決方法:看報錯信息在低幾行,從這一行往上找錯誤

2.類型錯誤

name = '張三'
fond = 1
print(name + '喜歡' + fond)

TypeError: must be str,not int

類型錯誤:必須是一個字符串,不能是數字

解決方法:使用+拼接的時候,必須使用字符串,或者將數字轉化成字符串

dic1.pop()

TypeError:pop expected at least 1 arguments,got 0

類型錯誤:pop方法期望得到至少一個參數,但是現在參數爲0

3.索引錯誤

list1 = ['outMan','小李子','諾蘭','皮克斯']
print(list1[5])

IndexError:list index out of range

索引錯誤:列表索引超出範圍

解決方法:查看列表的長度,索引要小於長度

4.縮進錯誤

if 'b' in list1:
        print('存在')
    else:
    print('不存在')

IndentationError:unindent does not match any outer indentation level

縮進錯誤:未知縮進不匹配任何縮進等級

if 'b' in list1:
        print('存在')
else:
print('不存在')

IndentationError: expected an indented block

縮進錯誤:期望一個縮進TAB

5.鍵錯誤

dic1 = {
    'name':'張三',
    'age': 17,
    'friend':['李四','王五','趙六','陳七']
}
print(dic1['fond'])

KeyError: 'fond'

鍵錯誤:沒有指定的鍵值

6.值錯誤

content = 'hello world'
result = content.index('2')
print(result)

ValueError: substring not found

值錯誤:子字符串未找到

7.屬性錯誤

tp1 = ({},[],(),1,2,3,'a','b',True)
tp1.remove()
print(tp1)

AttributeError: 'tuple' object has no attribute 'remove'

屬性錯誤:元組對象沒有屬性remove

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章