Python小知識————如何解決Python日常代碼中的一些BUG

    相信很多小夥伴在日常敲代碼的過程中,一不小心或者一不留神就會出錯,程序總會被各種各樣的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'])

   八個錯誤雖然全部錯誤沒有寫出來,但是如果掌握這八個,在日常的代碼過程中,能幫我們解決很多不必要的困擾,希望大家可以好好看一下。

未完待續.....





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