None
でない値を探索する
このステップでは、Python の None
と、None
でない値を識別する方法について学びます。None
は Python の特殊な値で、値が存在しないこと、または null 値を表します。変数に値が割り当てられていないこと、または関数が値を返さないことを示すためによく使用されます。
None
を扱う方法を理解することは、堅牢でエラーのない Python コードを書くために重要です。では、None
でない値を探索する Python スクリプトを作成して始めましょう。
-
VS Code エディタを開きます。
-
~/project
ディレクトリに explore_none.py
という名前の新しいファイルを作成します。
-
explore_none.py
ファイルに以下のコードを追加します。
## Assign None to a variable
my_variable = None
## Check if the variable is None
if my_variable is None:
print("The variable is None")
else:
print("The variable is not None")
## Assign a non-None value to the variable
my_variable = "Hello, LabEx!"
## Check again if the variable is None
if my_variable is None:
print("The variable is None")
else:
print("The variable is not None")
このスクリプトはまず、変数 my_variable
に None
を割り当てます。次に、if
文を使用して my_variable
が None
かどうかを確認します。もし None
なら、「The variable is None」と出力します。そうでなければ、「The variable is not None」と出力します。
次に、スクリプトは文字列「Hello, LabEx!」を my_variable
に割り当てます。そして、再度 my_variable
が None
かどうかを確認します。今回は、「The variable is not None」と出力されます。
-
explore_none.py
ファイルを保存します。
-
ターミナルで以下のコマンドを使用してスクリプトを実行します。
python explore_none.py
以下の出力が表示されるはずです。
The variable is None
The variable is not None
この出力は、変数が None
かどうかを確認する方法と、プログラムの実行中に変数の値がどのように変化するかを示しています。
では、スクリプトを修正して、さまざまな None
でない値を探索しましょう。
-
VS Code で explore_none.py
ファイルを開きます。
-
スクリプトを修正して以下を含めます。
## Assign None to a variable
my_variable = None
## Check if the variable is None
if my_variable is None:
print("The variable is None")
else:
print("The variable is not None")
## Assign an integer value to the variable
my_variable = 42
## Check again if the variable is None
if my_variable is None:
print("The variable is None")
else:
print("The variable is not None")
## Assign a boolean value to the variable
my_variable = True
## Check again if the variable is None
if my_variable is None:
print("The variable is None")
else:
print("The variable is not None")
この修正されたスクリプトでは、整数値 (42) とブール値 (True) を my_variable
に割り当てます。そのたびに、my_variable
が None
かどうかを確認します。出力は、各割り当て後に my_variable
が None
でないことを示します。
-
explore_none.py
ファイルを保存します。
-
同じコマンドを使用してスクリプトを再度実行します。
python explore_none.py
以下の出力が表示されるはずです。
The variable is None
The variable is not None
The variable is not None
この演習は、None
が特定の値であり、整数、文字列、ブール値などの他の値はすべて None
でない値と見なされることを示しています。この違いを理解することは、Python で条件文を書き、さまざまなタイプのデータを処理するために不可欠です。