初めてPythonを学んでよくある異常な間違い、いつも1か所あなたは出会うことができます!
8826 ワード
初心者Pythonでよくあるエラーコロン書き忘れ 誤用= エラー引き締め 変数は定義されていません 中英文入力法によるエラー 異なるデータ型の接続 インデックス位置問題 辞書に存在しないキーを使用 かっこ忘れ リークパラメータ 欠落依存ライブラリ pythonでキーワードを使用 符号化問題 1.コロンを書くのを忘れる
if、elif、else、for、while、def文の後に
2.誤用
3.誤ったインデント
Pythonはコードブロックをインデントで区別し、よくある誤った使い方:
4.変数が定義されていません
5.中国語と英語の入力方式によるエラー英文コロン 英文括弧 英文カンマ 英文単二重引用符
6.異なるデータ型の接続
文字列/リスト/タプルサポート
辞書/コレクションは接合をサポートしていません
7.インデックス位置の問題
8.辞書にないキーを使う
辞書オブジェクトへのアクセスキーは
しかし、キーが存在しない場合、KeyError:'zebra'になります.
このような状況を避けるためにgetメソッドを使用することができます
keyが存在しない場合、getはデフォルトでNoneを返します.
9.かっこ忘れ
関数に関数やメソッドが入力されると、カッコが漏れやすくなります
10.漏れパラメータ
11.依存ライブラリがありません
コンピュータに関連するライブラリがありません
12.pythonのキーワードを使用
try、except、def、class、object、None、True、Falseなど
13.ファイルエンコーディングの問題
encoding符号化パラメータのutf-8、gbkへの転送を試みる
符号化がutf-8とgbkではなく、一般的に符号化されていないことをエラーで示しています.ここでは、プログラムを実行するには、正しい都encodingを入力する必要があります.
pythonにはchardetライブラリがあり、コードを検出するために使用されます.
if、elif、else、for、while、def文の後に
:
を追加するのを忘れました.age = 42
if age == 42
print('Hello!')
File "", line 2
if age == 42
^
SyntaxError: invalid syntax
2.誤用
=
=` , `==
gender = ' '
if gender = ' ':
print('Man')
File "", line 2
if gender = ' ':
^
SyntaxError: invalid syntax
3.誤ったインデント
Pythonはコードブロックをインデントで区別し、よくある誤った使い方:
print('Hello!')
print('Howdy!')
File "", line 2
print('Howdy!')
^
IndentationError: unexpected indent
num = 25
if num == 25:
print('Hello!')
File "", line 3
print('Hello!')
^
IndentationError: expected an indented block
4.変数が定義されていません
if city in ['New York', 'Bei Jing', 'Tokyo']:
print('This is a mega city')
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
in
----> 1 if city in ['New York', 'Bei Jing', 'Tokyo']:
2 print('This is a mega city')
NameError: name 'city' is not defined
5.中国語と英語の入力方式によるエラー
if 5>3:
print('5 3 ')
File "", line 1
if 5>3:
^
SyntaxError: invalid character in identifier
if 5>3:
print('5 3 ')
File "", line 2
print('5 3 ')
^
SyntaxError: invalid character in identifier
spam = [1, 2,3]
File "", line 1
spam = [1, 2,3]
^
SyntaxError: invalid character in identifier
if 5>3:
print('5 3 ‘)
File "", line 2
print('5 3 ‘)
^
SyntaxError: EOL while scanning string literal
6.異なるデータ型の接続
文字列/リスト/タプルサポート
辞書/コレクションは接合をサポートしていません
'I have ' + 12 + ' eggs.'
#'I have {} eggs.'.format(12)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
----> 1 'I have ' + 12 + ' eggs.'
TypeError: can only concatenate str (not "int") to str
['a', 'b', 'c']+'def'
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
----> 1 ['a', 'b', 'c']+'def'
TypeError: can only concatenate list (not "str") to list
('a', 'b', 'c')+['a', 'b', 'c']
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
----> 1 ('a', 'b', 'c')+['a', 'b', 'c']
TypeError: can only concatenate tuple (not "list") to tuple
set(['a', 'b', 'c'])+set(['d', 'e'])
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
----> 1 set(['a', 'b', 'c'])+set(['d', 'e'])
TypeError: unsupported operand type(s) for +: 'set' and 'set'
grades1 = {'Mary':99, 'Henry':77}
grades2 = {'David':88, 'Unique':89}
grades1+grades2
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
2 grades2 = {'David':88, 'Unique':89}
3
----> 4 grades1+grades2
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
7.インデックス位置の問題
spam = ['cat', 'dog', 'mouse']
print(spam[5])
---------------------------------------------------------------------------
IndexError Traceback (most recent call last)
in
1 spam = ['cat', 'dog', 'mouse']
----> 2 print(spam[5])
IndexError: list index out of range
8.辞書にないキーを使う
辞書オブジェクトへのアクセスキーは
[]
を使用できます.しかし、キーが存在しない場合、KeyError:'zebra'になります.
spam = {'cat': 'Zophie',
'dog': 'Basil',
'mouse': 'Whiskers'}
print(spam['zebra'])
---------------------------------------------------------------------------
KeyError Traceback (most recent call last)
in
3 'mouse': 'Whiskers'}
4
----> 5 print(spam['zebra'])
KeyError: 'zebra'
このような状況を避けるためにgetメソッドを使用することができます
spam = {'cat': 'Zophie',
'dog': 'Basil',
'mouse': 'Whiskers'}
print(spam.get('zebra'))
None
keyが存在しない場合、getはデフォルトでNoneを返します.
9.かっこ忘れ
関数に関数やメソッドが入力されると、カッコが漏れやすくなります
spam = {'cat': 'Zophie',
'dog': 'Basil',
'mouse': 'Whiskers'}
print(spam.get('zebra')
File "", line 5
print(spam.get('zebra')
^
SyntaxError: unexpected EOF while parsing
10.漏れパラメータ
def diyadd(x, y, z):
return x+y+z
diyadd(1, 2)
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
in
2 return x+y+z
3
----> 4 diyadd(1, 2)
TypeError: diyadd() missing 1 required positional argument: 'z'
11.依存ライブラリがありません
コンピュータに関連するライブラリがありません
12.pythonのキーワードを使用
try、except、def、class、object、None、True、Falseなど
try = 5
print(try)
File "", line 1
try = 5
^
SyntaxError: invalid syntax
def = 6
print(6)
File "", line 1
def = 6
^
SyntaxError: invalid syntax
13.ファイルエンコーディングの問題
import pandas as pd
df = pd.read_csv('data/twitter .csv')
df.head()
encoding符号化パラメータのutf-8、gbkへの転送を試みる
df = pd.read_csv('data/twitter .csv', encoding='utf-8')
df.head()
符号化がutf-8とgbkではなく、一般的に符号化されていないことをエラーで示しています.ここでは、プログラムを実行するには、正しい都encodingを入力する必要があります.
pythonにはchardetライブラリがあり、コードを検出するために使用されます.
import chardet
binary_data = open('data/twitter .csv', 'rb').read()
chardet.detect(binary_data)
{'encoding': 'Windows-1252', 'confidence': 0.7291192008535122, 'language': ''