ななぶろ

-お役立ち情報を気楽に紹介するブログ-

Python分岐制御:初心者向け徹底解説と実践問題

www.amazon.co.jp

Python分岐制御:初心者向け徹底解説と実践問題

Pythonプログラミングにおいて、プログラムの流れを制御し、条件に応じて異なる処理を実行させる「分岐」は非常に重要な概念です。本記事では、Pythonの分岐構文について、初心者の方にも分かりやすく丁寧に解説します。基本的なif文から応用的なテクニックまで、具体的なコード例と豊富な実践問題を通して、分岐制御の理解を深めていきましょう。

はじめに

プログラミングの世界では、コンピュータは基本的に上から順番に命令を実行していきます。しかし、現実世界の状況は常に一定ではありません。「もし雨が降ったら傘を持っていく」「もし気温が30度以上ならエアコンをつける」といったように、条件によって行動を変える必要があります。Pythonの分岐構文は、まさにこの「条件によって行動を変える」ことを可能にするものです。特定の条件が真(True)であるかどうかを評価し、その結果に応じて異なるコードブロックを実行します。これにより、プログラムは状況に合わせて柔軟に対応できるようになります。

Introduction: In programming, computers generally execute commands sequentially from top to bottom. However, real-world situations are not always constant. Just like "take an umbrella if it rains" or "turn on the air conditioner if the temperature is 30 degrees or higher," we need to change our actions based on conditions. Python's branching syntax makes this "changing actions based on conditions" possible. It evaluates whether a specific condition is true and executes different code blocks accordingly, allowing programs to respond flexibly to various situations.

1. 分岐とは? - プログラムの流れを操る魔法

分岐は、プログラムの実行フローを制御する仕組みです。特定の条件が満たされるかどうかによって、どのコードブロックを実行するかを決定します。これにより、プログラムは状況に応じて異なる動作をすることができます。分岐構文を使用することで、プログラムに柔軟性と適応性を与えることができ、より複雑で実用的なアプリケーションを作成することが可能になります。

What is Branching? - The Magic of Controlling Program Flow: Branching is a mechanism for controlling the execution flow of a program. It determines which code block to execute based on whether certain conditions are met. This allows programs to perform different actions depending on the situation. By using branching syntax, you can give your program flexibility and adaptability, making it possible to create more complex and practical applications.

2. if 文 - 最も基本的な分岐

Pythonで最も基本的な分岐構文は if 文です。if 文の基本的な構造は以下の通りです。

if 条件:
    # 条件が真の場合に実行されるコード

条件は、評価結果が True または False となる式です。条件が True の場合のみ、インデントされたコードブロックが実行されます。Pythonでは、コロン (:) で if 文を終了し、その後の行はインデント(通常はスペース4つ)することで、if 文の処理範囲を示します。

例:

age = 20

if age >= 18:
    print("あなたは成人です")

この例では、変数 age が 18 以上であるかどうかを評価しています。age が 20 なので条件は True となり、「あなたは成人です」と表示されます。

The if Statement - The Most Basic Branching: The most basic branching syntax in Python is the if statement. The basic structure of an if statement is as follows:

if condition:
    # Code to be executed if the condition is true

The condition is an expression that evaluates to True or False. Only when the condition is True will the indented code block be executed. In Python, the if statement ends with a colon (:) and subsequent lines are indented (usually 4 spaces) to indicate the processing range of the if statement.

Example:

age = 20

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

In this example, it evaluates whether the variable age is greater than or equal to 18. Since age is 20, the condition is True and "You are an adult." is displayed.

3. else 文 - 条件が偽の場合の処理

if 文に加えて、条件が False の場合に実行するコードブロックを指定するには else 文を使用します。else 文の構造は以下の通りです。

if 条件:
    # 条件が真の場合に実行されるコード
else:
    # 条件が偽の場合に実行されるコード

else ブロックは、if の条件が False である場合にのみ実行されます。これにより、プログラムは条件に応じて異なる処理を適切に選択することができます。

例:

age = 15

if age >= 18:
    print("あなたは成人です")
else:
    print("あなたは未成年です")

この例では、age が 18 以上であるかどうかを評価しています。age が 15 なので条件は False となり、「あなたは未成年です」と表示されます。

The else Statement - Processing When the Condition is False: In addition to the if statement, you can use the else statement to specify a code block that will be executed when the condition is false. The structure of the else statement is as follows:

if condition:
    # Code to be executed if the condition is true
else:
    # Code to be executed if the condition is false

The else block is only executed when the condition in the if statement is False. This allows the program to appropriately select different processing based on the condition.

Example:

age = 15

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

In this example, it evaluates whether age is greater than or equal to 18. Since age is 15, the condition is False and "You are a minor." is displayed.

4. elif 文 - 複数の条件分岐

複数の条件に基づいて処理を分けたい場合は、elif (else if) 文を使用します。elif 文は、前の if または elif の条件が False であり、新しい条件が True である場合に実行されるコードブロックを指定します。elif を複数使用することで、複雑な条件分岐を簡潔に記述することができます。

if 条件1:
    # 条件1が真の場合に実行されるコード
elif 条件2:
    # 条件1が偽で、条件2が真の場合に実行されるコード
else:
    # すべての条件が偽の場合に実行されるコード

例:

score = 75

if score >= 80:
    print("Aランク")
elif score >= 60:
    print("Bランク")
elif score >= 40:
    print("Cランク")
else:
    print("Dランク")

この例では、score の値に応じて異なるランクを表示しています。score が 75 なので、最初の if 条件は False ですが、2番目の elif 条件は True となり、「Bランク」と表示されます。

The elif Statement - Multiple Condition Branches: If you want to divide processing based on multiple conditions, use the elif (else if) statement. The elif statement specifies a code block that will be executed when the previous if or elif condition is False and the new condition is True. By using multiple elif statements, you can concisely describe complex conditional branching.

Example:

score = 75

if score >= 80:
    print("A rank")
elif score >= 60:
    print("B rank")
elif score >= 40:
    print("C rank")
else:
    print("D rank")

In this example, it displays different ranks depending on the value of score. Since score is 75, the first if condition is False, but the second elif condition is True, and "B rank" is displayed.

5. ネストされた if 文 - より複雑な条件分岐

if 文の中にさらに if 文を記述することで、ネストされた if 文を作成できます。これにより、より複雑な条件分岐を実現できます。ネストされた if 文は、複数の条件を組み合わせることで、より詳細な制御を行うことができますが、コードの可読性を損なわないように注意が必要です。

if 条件1:
    # 条件1が真の場合に実行されるコード
    if 条件2:
        # 条件1と条件2の両方が真の場合に実行されるコード
    else:
        # 条件1は真だが、条件2は偽の場合に実行されるコード
else:
    # 条件1が偽の場合に実行されるコード

例:

age = 25
has_license = True

if age >= 18:
    if has_license:
        print("運転できます")
    else:
        print("免許が必要です")
else:
    print("まだ運転できません")

この例では、まず age が 18 以上であるかどうかを評価し、次に has_license が True であるかどうかを評価しています。両方の条件が True の場合のみ、「運転できます」と表示されます。

Nested if Statements - More Complex Condition Branching: You can create nested if statements by writing an if statement within another if statement. This allows you to achieve more complex conditional branching. Nested if statements allow for more detailed control by combining multiple conditions, but be careful not to compromise code readability.

Example:

age = 25
has_license = True

if age >= 18:
    if has_license:
        print("You can drive.")
    else:
        print("You need a license.")
else:
    print("You are not yet old enough to drive.")

In this example, it first evaluates whether age is greater than or equal to 18 and then evaluates whether has_license is True. Only when both conditions are True will "You can drive." be displayed.

6. 条件式 - より簡潔な記述

Pythonには、条件式と呼ばれる、if-else 文を1行で記述できる機能があります。これは、簡単な条件分岐を簡潔に表現するのに役立ちます。

結果 = 値1 if 条件 else2

この構文は、「もし条件が True なら値1 を、False なら値2 を 結果 に代入する」という意味になります。

例:

age = 10
status = "未成年" if age < 18 else "成人"
print(status)  # 出力: 未成年

条件式は、コードの可読性を向上させることができますが、複雑な条件分岐には適していません。

Conditional Expressions - More Concise Descriptions: Python has a feature called conditional expressions that allows you to write if-else statements in one line. This is useful for concisely expressing simple conditional branching.

result = value1 if condition else value2

This syntax means, "If the condition is True, assign value1 to result, otherwise assign value2."

Example:

age = 10
status = "minor" if age < 18 else "adult"
print(status)  # Output: minor

Conditional expressions can improve code readability, but they are not suitable for complex conditional branching.

7. ブール演算子 - 複数の条件の組み合わせ

複数の条件を組み合わせて評価するには、ブール演算子を使用します。Pythonには、以下のブール演算子が用意されています。

  • and: 論理積 (両方の条件が True の場合に True)
  • or: 論理和 (少なくとも一方の条件が True の場合に True)
  • not: 否定 (条件を反転させる)

これらの演算子を使用することで、より複雑な条件を表現することができます。

例:

age = 20
is_student = True

if age >= 18 and is_student:
    print("学生割引を利用できます")

if age < 18 or is_student:
    print("学生または未成年です")

if not is_student:
    print("学生ではありません")

Boolean Operators - Combining Multiple Conditions: To combine multiple conditions and evaluate them, use boolean operators. Python provides the following boolean operators:

  • and: Logical AND (True if both conditions are True)
  • or: Logical OR (True if at least one condition is True)
  • not: NOT (inverts a condition)

By using these operators, you can express more complex conditions.

Example:

age = 20
is_student = True

if age >= 18 and is_student:
    print("You are eligible for student discount.")

if age < 18 or is_student:
    print("Student or minor.")

if not is_student:
    print("Not a student.")

8. in 演算子 - メンバーシップテスト

in 演算子は、ある値がシーケンス(リスト、タプル、文字列など)に含まれているかどうかを判定します。これは、特定の要素が存在するかどうかを確認するのに役立ちます。

例:

fruits = ["apple", "banana", "orange"]

if "banana" in fruits:
    print("バナナがあります")

if "grape" not in fruits:
    print("ぶどうはありません")

The in Operator - Membership Testing: The in operator checks whether a value is contained within a sequence (list, tuple, string, etc.). This is useful for verifying the existence of specific elements.

Example:

fruits = ["apple", "banana", "orange"]

if "banana" in fruits:
    print("There is a banana.")

if "grape" not in fruits:
    print("There is no grape.")

9. is 演算子 - オブジェクトの同一性テスト

is 演算子は、2つのオブジェクトが同じメモリ位置にあるかどうかを判定します。これは、値が等しいだけでなく、実際に同じオブジェクトであるかをチェックするのに使用されます。is 演算子は、主にオブジェクトの比較に使用され、数値や文字列などの不変オブジェクトの比較には == 演算子を使用することが一般的です。

例:

a = [1, 2, 3]
b = a  # b は a と同じオブジェクトを参照

if a is b:
    print("a と b は同じオブジェクトです")

c = [1, 2, 3] # c は a とは異なるオブジェクト

if a is c:
    print("a と c は同じオブジェクトです")  # これは実行されません
else:
    print("a と c は異なるオブジェクトです")

The is Operator - Object Identity Testing: The is operator checks whether two objects are located at the same memory address. This is used to check if they are actually the same object, not just equal in value. The is operator is primarily used for comparing objects, and it's common to use the == operator when comparing immutable objects like numbers and strings.

Example:

a = [1, 2, 3]
b = a  # b refers to the same object as a

if a is b:
    print("a and b are the same object")

c = [1, 2, 3] # c is a different object than a

if a is c:
    print("a and c are the same object")  # This will not be executed
else:
    print("a and c are different objects")

10. == 演算子 - 値の等価性テスト

== 演算子は、2つのオブジェクトの値が等しいかどうかを判定します。これは is 演算子とは異なり、値が同じであれば True を返します。数値や文字列などの不変オブジェクトの比較には == 演算子を使用することが一般的です。

例:

a = [1, 2, 3]
b = [1, 2, 3]

if a == b:
    print("a と b の値は等しいです")

The == Operator - Value Equality Testing: The == operator checks whether the values of two objects are equal. This is different from the is operator, which returns True if the values are the same. It's common to use the == operator when comparing immutable objects like numbers and strings.

Example:

a = [1, 2, 3]
b = [1, 2, 3]

if a == b:
    print("The values of a and b are equal")

練習問題 - 分岐の理解を深める

ここからは、実際にコードを書いて分岐の理解を深めるための練習問題をいくつか紹介します。これらの問題を解くことで、様々な状況における条件分岐の応用力を高めることができます。

  1. 偶数・奇数の判定: 整数を入力として受け取り、それが偶数か奇数かを判定するプログラムを作成してください。
    • input() 関数を使用してユーザーから入力を取得します。
    • 入力が整数であることを確認するために try-except ブロックを使用します。
    • % (剰余) 演算子を使用して、入力が偶数か奇数を判定します。
  2. 年齢によるメッセージ表示: 年齢を入力として受け取り、以下の条件で異なるメッセージを表示するプログラムを作成してください。
    • 18歳未満: 「未成年です」
    • 18歳以上59歳未満: 「働き盛りです」
    • 60歳以上: 「高齢者です」
  3. 成績評価: 試験の点数を入力として受け取り、以下の条件で成績を評価するプログラムを作成してください。
    • 80点以上: Aランク
    • 60点以上: Bランク
    • 40点以上: Cランク
    • 40点未満: Dランク
  4. うるう年の判定: 西暦を入力として受け取り、それがうるう年かどうかを判定するプログラムを作成してください。
    • うるう年は、西暦が4で割り切れる年です。ただし、100で割り切れる年はうるう年ではありません。また、400で割り切れる年はうるう年です。
  5. BMIの計算と判定: 身長と体重を入力として受け取り、BMIを計算し、以下の条件で肥満度を判定するプログラムを作成してください。
    • 18.5未満: 低体重
    • 18.5以上25未満: 標準体重
    • 25以上30未満: 過体重
    • 30以上: 肥満
  6. パスワードの強度判定: パスワードを入力として受け取り、以下の条件でパスワードの強度を判定するプログラムを作成してください。
    • 8文字以上: 強固
    • 6文字以上8文字未満: 普通
    • 6文字未満: 弱い
  7. 三角形の種類の判定: 三角形の3辺の長さを入力として受け取り、それが正三角形、二等辺三角形、または不等辺三角形であるかを判定するプログラムを作成してください。
  8. 電卓: 2つの数値と演算子(+、-、*、/)を入力として受け取り、計算結果を表示するプログラムを作成してください。
    • 入力された演算子が有効であることを確認します。
    • 割り算を行う際には、0で割ることを防ぎます。
  9. 曜日判定: 整数 (1~7) を入力として受け取り、対応する曜日を表示するプログラムを作成してください。
  10. ローマ数字の変換: ローマ数字(I, V, X, L, C, D, M)を入力として受け取り、その数値に変換するプログラムを作成してください。

これらの練習問題を解くことで、分岐構文の理解を深め、より複雑なプログラムを作成できるようになります。

まとめ - 分岐をマスターして、プログラムを自由に操ろう!

本記事では、Pythonにおける分岐の基礎から応用までを解説しました。if, else, elif 文の使い方、ネストされた if 文、条件式、ブール演算子などを理解することで、プログラムの流れを制御し、状況に応じて異なる処理を実行できるようになります。

これらの知識を基に、様々な問題を解決するプログラムを作成してみてください。分岐構文の習得は、Pythonプログラミングの重要な一歩です。頑張ってください!

Q&A - 分岐に関するよくある質問

  • Q: if 文と elif 文は何が違うのですか?
    • A: if 文は最初の条件を評価し、それが True の場合にのみコードブロックを実行します。一方、elif 文は前の if または elif の条件が False であり、新しい条件が True である場合に実行されるコードブロックを指定します。複数の条件を順番に評価する必要がある場合に elif 文を使用します。
  • Q: ネストされた if 文はいつ使用すれば良いですか?
    • A: 複数の条件を組み合わせることで、より詳細な制御を行いたい場合にネストされた if 文を使用します。ただし、コードの可読性を損なわないように注意が必要です。複雑すぎるネストは避けるべきです。
  • Q: 条件式はどのような場面で役立ちますか?
    • A: 簡単な条件分岐を簡潔に表現したい場合に条件式が役立ちます。例えば、変数の値に応じて異なる値を代入する場合などに使用できます。
  • Q: ブール演算子は何のために使いますか?
    • A: 複数の条件を組み合わせて評価するためにブール演算子を使用します。and, or, not を使用することで、複雑な条件を表現することができます。

この解説が、あなたのPython学習の一助となれば幸いです。