初心者のための Python If Else 文

条件文はプログラミングの基本的な側面であり、特定の条件に基づいて異なるコードを実行できます。Python では、if および else 文を使用してコード内で決定を下します。このガイドでは、if および else 文の構文や一般的な使用パターンなど、基本的な使用方法について説明します。

基本的なif文

if ステートメントは条件を評価し、条件が True の場合、if ステートメント内のコード ブロックが実行されます。

# Basic if statement
age = 18
if age >= 18:
    print("You are an adult.")

If Else 文

else ステートメントは、if 条件が False と評価された場合に実行される代替コード ブロックを提供します。

# If else statement
age = 16
if age >= 18:
    print("You are an adult.")
else:
    print("You are a minor.")

If Elif Else ステートメント

elif ("else if" の略) ステートメントを使用すると、複数の条件をチェックできます。これは if ステートメントの後に続き、2 つ以上の条件を評価する必要がある場合に使用されます。

# If elif else statement
temperature = 75
if temperature > 80:
    print("It's hot outside.")
elif temperature > 60:
    print("It's warm outside.")
else:
    print("It's cool outside.")

比較演算子

比較演算子は、値を比較するために if ステートメントで使用されます。一般的な演算子をいくつか示します。

  • == - 等しい
  • != - 等しくない
  • > - より大きい
  • < - より小さい
  • >= - より大きいか等しい
  • <= - 以下
# Using comparison operators
x = 10
y = 20
if x == y:
    print("x and y are equal.")
elif x > y:
    print("x is greater than y.")
else:
    print("x is less than y.")

論理演算子

論理演算子は複数の条件を組み合わせます。次のようなものがあります。

  • and - 両方の条件がTrueの場合、Trueを返します。
  • or - 少なくとも1つの条件がTrueの場合、Trueを返します。
  • not - 条件がFalseの場合、Trueを返します。
# Using logical operators
x = 10
y = 20
if x < 15 and y > 15:
    print("Both conditions are met.")
if x < 15 or y < 15:
    print("At least one condition is met.")
if not (x > 15):
    print("x is not greater than 15.")

ネストされた if 文

より複雑なロジックを処理するために、if ステートメントを他の if ステートメント内にネストすることができます。

# Nested if statements
age = 25
if age >= 18:
    if age >= 21:
        print("You are legally an adult and can drink alcohol.")
    else:
        print("You are an adult but cannot drink alcohol.")
else:
    print("You are not an adult.")

結論

ifelseelif ステートメントの使い方を理解することは、Python プログラムで決定を下す上で非常に重要です。比較演算子と論理演算子を使用したり、条件をネストしたりすることで、さまざまなシナリオに対応し、より動的で応答性の高いコードを作成できます。これらの条件ステートメントの使用を練習して、問題解決スキルを高め、より効果的な Python コードを記述しましょう。