NameError を修正: Python で変数が定義されていません
この記事では、Python の NameError の原因と、特定のエラー NameError: 変数が定義されていません を修正する方法について説明します。
Python の変数のスコープ
変数のスコープは、特定のブロックからアクセスできるかどうかに関係なく、変数にアクセシビリティ制約を実装します。 一部の変数の有効期間は特定のブロック内だけですが、他の変数はプログラム全体でアクセスできます。
例を通してそれを理解しましょう:
# global scope
a = 3
# Function to add two numbers
def displayScope():
# local varaible
b = 2
# sum a and b
c = a + b
print("The sum of a & b = ", c)
displayScope()
出力:
The sum of a & b = 5
この例では、変数 a が先頭で定義されており、ブロックで囲まれていないため、プログラム全体でアクセスできます。 ただし、変数 b は関数ブロック内でローカルに定義されています。 したがって、ブロックの外からはアクセスできません。
Python の NameError
Python では、変数、ライブラリ、関数、または一重引用符または二重引用符のない文字列の実行中に実行時に NameError が発生します。これらはコード内の宣言のない型です。 次に、スコープがローカルでグローバルにアクセスできない関数または変数を呼び出すと、Python インタープリターは NameError をスローし、name 'name' が定義されていません と伝えます。
Python での NameError の原因
NameError の原因は、無効な関数、変数、またはライブラリへの呼び出しです。 理由を明確に理解するために、例を挙げてみましょう。
# invalid funciton call
def test_ftn():
return "Test function"
print(test_ft()) # calling the the function which does not exist
# printing invalid varaible
name = "Zeeshan Afridi"
print(Name) # printing variable `Name` which does not exist
どちらも Python の NameError の原因です。最初の例では、使用できない関数を呼び出したためです。 関数名は test_ftn ですが、test_ft 関数を呼び出しています。
2 番目の例では、name 変数が文字列 Zeeshan Afridi に割り当てられていますが、プログラムで宣言されていない Name を出力しています。 これが、NameError: name 'test_ft' is not defined を取得した理由です。
Python の NameError: Variable is not defined を修正
上記の例では、スコープ外の変数を呼び出したため、NameError が発生しました。 この NameError: variable is not defined を修正する方法を見てみましょう。
# global scope
a = 3
# Function to add two numbers
def displayScope():
# local varaible
b = 2
print("The value of a = ", a)
print("The value of b = ", b)
出力:
The value of a = 3
NameError: name 'b' is not defined
上記のコードは、プログラム全体でアクセスできるため、a の値を表示しています。 一方、変数 b はローカルで定義されているため、関数 displayScope() にのみ認識されます。 スコープ外にアクセスすることはできません。
これにより、エラー NameError: name 'b' is not defined が発生しました。
幸いなことに、Python はこの問題を解決するために global 予約キーワードを導入しました。 この global 予約キーワードは、ローカル変数のスコープを拡大して、プログラム全体で変数にグローバルにアクセスできるようにするために使用されます。
例を通してそれを理解しましょう:
# global scope
a = 3
# Function to add two numbers
def displayScope():
# local scope
global c
z = 2
c = a + b
print("The value of c =", c)
出力:
The value of c = 5
この例では、変数 c は displayScope() のローカル スコープ内で定義されていますが、魔法のキーワード global によりグローバルにアクセスできます。 現在、c は global として定義されているため、どこからでもアクセスできます。
Zeeshan is a detail oriented software engineer that helps companies and individuals make their lives and easier with software solutions.
LinkedIn関連記事 - Python Error
- AttributeError の解決: 'list' オブジェクト属性 'append' は読み取り専用です
- AttributeError の解決: Python で 'Nonetype' オブジェクトに属性 'Group' がありません
- AttributeError: 'generator' オブジェクトに Python の 'next' 属性がありません
- AttributeError: 'numpy.ndarray' オブジェクトに Python の 'Append' 属性がありません
- AttributeError: Int オブジェクトに属性がありません
- AttributeError: Python で 'Dict' オブジェクトに属性 'Append' がありません
