if 文の実装
このステップでは、Python で if
文を使用してプログラムの流れを制御する方法を学びます。if
文を使用すると、特定の条件が真の場合にのみコードブロックを実行することができます。
if
文の基本的な構文は次の通りです。
if condition:
## Code to execute if the condition is true
condition
は、True
または False
に評価されるブール式です。条件が True
の場合、インデントされたブロック内のコードが実行されます。条件が False
の場合、ブロック内のコードはスキップされます。
if
文の動作を示す簡単な例を作成しましょう。前のステップで作成した conditions.py
スクリプトを変更します。
- VS Code で
conditions.py
ファイルを開きます。
- コードを変更して以下を含めます。
x = 5
y = 10
if x < y:
print("x is less than y")
このコードは、x
が y
より小さいかどうかをチェックします。もし小さければ、「x is less than y」というメッセージを出力します。
変更を保存し、スクリプトを再度実行します。
python ~/project/conditions.py
以下の出力が表示されるはずです。
x is less than y
この出力は、条件 x < y
が真であったため、if
文内のコードが実行されたことを示しています。
if
文に else
句を追加することもできます。else
句を使用すると、条件が偽の場合に異なるコードブロックを実行することができます。
if-else
文の構文は次の通りです。
if condition:
## Code to execute if the condition is true
else:
## Code to execute if the condition is false
conditions.py
スクリプトを変更して else
句を含めましょう。
- VS Code で
conditions.py
ファイルを開きます。
- コードを変更して以下を含めます。
x = 15
y = 10
if x < y:
print("x is less than y")
else:
print("x is greater than or equal to y")
このコードは、x
が y
より小さいかどうかをチェックします。もし小さければ、「x is less than y」というメッセージを出力します。そうでなければ、「x is greater than or equal to y」というメッセージを出力します。
変更を保存し、スクリプトを再度実行します。
python ~/project/conditions.py
以下の出力が表示されるはずです。
x is greater than or equal to y
この出力は、条件 x < y
が偽であったため、else
句内のコードが実行されたことを示しています。
最後に、if
文に elif
(else if) 句を追加することができます。elif
句を使用すると、複数の条件を順番にチェックすることができます。
if-elif-else
文の構文は次の通りです。
if condition1:
## Code to execute if condition1 is true
elif condition2:
## Code to execute if condition1 is false and condition2 is true
else:
## Code to execute if both condition1 and condition2 are false
conditions.py
スクリプトを変更して elif
句を含めましょう。
- VS Code で
conditions.py
ファイルを開きます。
- コードを変更して以下を含めます。
x = 10
y = 10
if x < y:
print("x is less than y")
elif x > y:
print("x is greater than y")
else:
print("x is equal to y")
このコードは、x
が y
より小さいかどうかをチェックします。もし小さければ、「x is less than y」というメッセージを出力します。x
が y
より大きい場合、「x is greater than y」というメッセージを出力します。そうでなければ、「x is equal to y」というメッセージを出力します。
変更を保存し、スクリプトを再度実行します。
python ~/project/conditions.py
以下の出力が表示されるはずです。
x is equal to y
この出力は、条件 x < y
と x > y
の両方が偽であったため、else
句内のコードが実行されたことを示しています。
if
文は、意思決定を行い、さまざまな状況に対応できるプログラムを作成するために不可欠です。次のステップでは、and
および or
演算子を使用して if
文内で複数の条件を組み合わせる方法を学びます。