1. <strong id="7actg"></strong>
    2. <table id="7actg"></table>

    3. <address id="7actg"></address>
      <address id="7actg"></address>
      1. <object id="7actg"><tt id="7actg"></tt></object>

        初學(xué)Python常見異常錯(cuò)誤,總有一處你會(huì)遇到!

        共 4677字,需瀏覽 10分鐘

         ·

        2019-10-06 23:20

        c0e53e762ed34c02af83f073856a362b.webp

        初學(xué)Python常見錯(cuò)誤

        1. 忘記寫冒號

        2. 誤用=

        3. 錯(cuò)誤 縮緊

        4. 變量沒有定義

        5. 中英文輸入法導(dǎo)致的錯(cuò)誤

        6. 不同數(shù)據(jù)類型的拼接

        7. 索引位置問題

        8. 使用字典中不存在的鍵

        9. 忘了括號

        10. 漏傳參數(shù)

        11. 缺失依賴庫

        12. 使用了python中對關(guān)鍵詞

        13. 編碼問題

        1. 忘記寫冒號

        在 if、elif、else、for、while、def語句后面忘記添加 :

        1. age = 42

        2. if age == 42

        3. print('Hello!')

        1. File"", line 2

        2. if age == 42

        3. ^

        4. SyntaxError: invalid syntax

        2. 誤用?=

        = 是賦值操作,而判斷兩個(gè)值是否相等是 ==

        1. gender = '男'

        2. if gender = '男':

        3. print('Man')

        1. File"", line 2

        2. if gender = '男':

        3. ^

        4. SyntaxError: invalid syntax

        3. 錯(cuò)誤的縮進(jìn)

        Python用縮進(jìn)區(qū)分代碼塊,常見的錯(cuò)誤用法:

        1. print('Hello!')

        2. print('Howdy!')

        1. File"", line 2

        2. print('Howdy!')

        3. ^

        4. IndentationError: unexpected indent

        1. num = 25

        2. if num == 25:

        3. print('Hello!')

        1. File"", line 3

        2. print('Hello!')

        3. ^

        4. IndentationError: expected an indented block

        4. 變量沒有定義

        1. if city in ['New York', 'Bei Jing', 'Tokyo']:

        2. print('This is a mega city')

        1. ---------------------------------------------------------------------------


        2. NameErrorTraceback (most recent call last)


        3. 22-a81fd2e7a0fd> in

        4. ----> 1if city in ['New York', 'Bei Jing', 'Tokyo']:

        5. 2print('This is a mega city')

        1. NameError: name 'city'isnotdefined

        5. 中英文輸入法導(dǎo)致的錯(cuò)誤

        • 英文冒號

        • 英文括號

        • 英文逗號

        • 英文單雙引號

        1. if5>3

        2. print('5比3大')

        1. File"", line 1

        2. if5>3

        3. ^

        4. SyntaxError: invalid character in identifier

        1. if5>3:

        2. print('5比3大'

        1. File"", line 2

        2. print('5比3大'

        3. ^

        4. SyntaxError: invalid character in identifier

        1. spam = [1, 23]

        1. File"", line 1

        2. spam = [1, 2,3]

        3. ^

        4. SyntaxError: invalid character in identifier

        1. if5>3:

        2. print('5比3大‘)

        1. File"", line 2

        2. print('5比3大‘)

        3. ^

        4. SyntaxError: EOL while scanning string literal

        6. 不同數(shù)據(jù)類型的拼接

        字符串/列表/元組 支持拼接

        字典/集合不支持拼接

        1. 'I have ' + 12 + ' eggs.'

        2. #'I have {} eggs.'.format(12)

        1. ---------------------------------------------------------------------------


        2. TypeErrorTraceback (most recent call last)


        3. 29-20c7c89a2ec6> in

        4. ----> 1'I have ' + 12 + ' eggs.'

        1. TypeError: can only concatenate str (not"int") to str

        1. ['a', 'b', 'c']+'def'

        1. ---------------------------------------------------------------------------


        2. TypeErrorTraceback (most recent call last)


        3. 31-0e8919333d6b> in

        4. ----> 1 ['a', 'b', 'c']+'def'

        1. TypeError: can only concatenate list (not"str") to list

        1. ('a', 'b', 'c')+['a', 'b', 'c']

        1. ---------------------------------------------------------------------------


        2. TypeErrorTraceback (most recent call last)


        3. 33-90742621216d> in

        4. ----> 1 ('a', 'b', 'c')+['a', 'b', 'c']

        1. TypeError: can only concatenate tuple (not"list") to tuple

        1. set(['a', 'b', 'c'])+set(['d', 'e'])

        1. ---------------------------------------------------------------------------


        2. TypeErrorTraceback (most recent call last)


        3. 35-ddf5fb1e6c8c> in

        4. ----> 1set(['a', 'b', 'c'])+set(['d', 'e'])

        1. TypeError: unsupported operand type(s) for +: 'set'and'set'

        1. grades1 = {'Mary':99, 'Henry':77}

        2. grades2 = {'David':88, 'Unique':89}


        3. grades1+grades2

        1. ---------------------------------------------------------------------------


        2. TypeErrorTraceback (most recent call last)


        3. 36-1b1456844331> in

        4. 2 grades2 = {'David':88, 'Unique':89}

        5. 3

        6. ----> 4 grades1+grades2

        1. TypeError: unsupported operand type(s) for +: 'dict'and'dict'

        7. 索引位置問題

        1. spam = ['cat', 'dog', 'mouse']

        2. print(spam[5])

        1. ---------------------------------------------------------------------------


        2. IndexErrorTraceback (most recent call last)


        3. 38-e0a79346266d> in

        4. 1 spam = ['cat', 'dog', 'mouse']

        5. ----> 2print(spam[5])

        1. IndexError: list index out of range

        8. 使用字典中不存在的鍵

        在字典對象中訪問 key 可以使用 [],

        但是如果該 key 不存在,就會(huì)導(dǎo)致:KeyError: 'zebra'

        1. spam = {'cat': 'Zophie',

        2. 'dog': 'Basil',

        3. 'mouse': 'Whiskers'}


        4. print(spam['zebra'])

        1. ---------------------------------------------------------------------------


        2. KeyErrorTraceback (most recent call last)


        3. 39-92c9b44ff034> in

        4. 3'mouse': 'Whiskers'}

        5. 4

        6. ----> 5print(spam['zebra'])

        1. KeyError: 'zebra'

        為了避免這種情況,可以使用 get 方法

        1. spam = {'cat': 'Zophie',

        2. 'dog': 'Basil',

        3. 'mouse': 'Whiskers'}


        4. print(spam.get('zebra'))

        1. None

        key 不存在時(shí),get 默認(rèn)返回 None

        9. 忘了括號

        當(dāng)函數(shù)中傳入的是函數(shù)或者方法時(shí),容易漏寫括號

        1. spam = {'cat': 'Zophie',

        2. 'dog': 'Basil',

        3. 'mouse': 'Whiskers'}


        4. print(spam.get('zebra')

        1. File"", line 5

        2. print(spam.get('zebra')

        3. ^

        4. SyntaxError: unexpected EOF while parsing

        10. 漏傳參數(shù)

        1. def diyadd(x, y, z):

        2. return x+y+z


        3. diyadd(1, 2)

        1. ---------------------------------------------------------------------------


        2. TypeErrorTraceback (most recent call last)


        3. 44-7184f3f906ca> in

        4. 2return x+y+z

        5. 3

        6. ----> 4 diyadd(1, 2)

        1. TypeError: diyadd() missing 1 required positional argument: 'z'

        11. 缺失依賴庫

        電腦中沒有相關(guān)的庫

        12. 使用了python中的關(guān)鍵詞

        如try、except、def、class、object、None、True、False等

        1. try = 5

        2. print(try)

        1. File"", line 1

        2. try = 5

        3. ^

        4. SyntaxError: invalid syntax

        1. def = 6

        2. print(6)

        1. File"", line 1

        2. def = 6

        3. ^

        4. SyntaxError: invalid syntax

        13. 文件編碼問題

        1. import pandas as pd


        2. df = pd.read_csv('data/twitter情感分析數(shù)據(jù)集.csv')

        3. df.head()

        嘗試encoding編碼參數(shù)傳入utf-8、gbk

        1. df = pd.read_csv('data/twitter情感分析數(shù)據(jù)集.csv', encoding='utf-8')

        2. df.head()

        都報(bào)錯(cuò)說明編碼不是utf-8和gbk,而是不常見都編碼,這里我們需要傳入正確都encoding,才能讓程序運(yùn)行。

        python有個(gè)chardet庫,專門用來偵測編碼。

        1. import chardet


        2. binary_data = open('data/twitter情感分析數(shù)據(jù)集.csv', 'rb').read()

        3. chardet.detect(binary_data)

        1. {'encoding': 'Windows-1252', 'confidence': 0.7291192008535122, 'language': ''}

        瀏覽 91
        點(diǎn)贊
        評論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        評論
        圖片
        表情
        推薦
        點(diǎn)贊
        評論
        收藏
        分享

        手機(jī)掃一掃分享

        分享
        舉報(bào)
        1. <strong id="7actg"></strong>
        2. <table id="7actg"></table>

        3. <address id="7actg"></address>
          <address id="7actg"></address>
          1. <object id="7actg"><tt id="7actg"></tt></object>
            初尝禁果hd未删减版 | 免费黄色做爱视频 | 久久婷婷色 | 日韩精品一区二区三区不卡 | 免费无遮挡 视频一挑二 | 日韩性爱影院 | 免费A级片视频 | 拳头伸进身体里宫交3p | 修仙高肉h爽文bl | 性猛交xxxx乱大交孕妇2十 |