ななぶろ

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

Pythonプログラム練習問題10問:条件分岐の基礎と応用

www.amazon.co.jp

Pythonプログラム練習問題10問:条件分岐の基礎と応用

Pythonプログラミングにおいて、条件分岐は非常に重要な概念です。プログラムの流れを制御し、特定の条件に基づいて異なる処理を実行させることで、柔軟で複雑なロジックを実現できます。本記事では、条件分岐の基礎から応用までを理解できるよう、練習問題10問を通して解説します。Python初心者の方でもステップアップできる内容を目指していますので、ぜひ挑戦してみてください。

1. 条件分岐とは?

まず、条件分岐とは何かについて説明します。プログラムは通常、上から順番に処理を実行していきますが、条件分岐を使うと、「もし〇〇ならば、△△をする」といった条件に基づいて処理を切り替えることができます。これにより、様々な状況に対応したプログラムを作成できます。

Pythonにおける主な条件分岐の構文は以下の通りです。

  • if 文: 条件が真 (True) の場合にのみ、そのブロック内のコードを実行します。
  • elif 文: if 文の条件が偽 (False) であり、かつ elif 文の条件が真の場合に、そのブロック内のコードを実行します。複数使用できます。
  • else 文: if 文および elif 文のすべての条件が偽の場合に、そのブロック内のコードを実行します。

これらの構文を組み合わせることで、複雑な条件分岐処理を実現できます。

Explanation in English:

First, let's explain what conditional branching is. In a program, instructions are typically executed sequentially from top to bottom. However, using conditional branching allows you to switch the execution flow based on conditions like "If condition A is true, then do action B." This enables you to create programs that can handle various situations.

The main syntax for conditional branching in Python includes:

  • if statement: Executes the code block only if the condition is True.
  • elif statement: Executes the code block if the if statement's condition is False and the elif statement's condition is True. You can use multiple elif statements.
  • else statement: Executes the code block if all conditions in the if and elif statements are False.

By combining these syntax elements, you can implement complex conditional branching logic.

2. 条件式 (Boolean Expression) とは?

条件分岐で使用する条件式とは、真 (True) または偽 (False) のいずれかの結果となる式のことを指します。例えば、x > 5y == 10 などが条件式です。Pythonでは、これらの条件式を評価し、その結果に基づいて処理を分岐させます。

Pythonでよく使われる比較演算子と論理演算子は以下の通りです。

  • 比較演算子:
    • ==: 等しい (Equal)
    • !=: 等しくない (Not equal)
    • >: より大きい (Greater than)
    • <: より小さい (Less than)
    • >=: 以上 (Greater than or equal to)
    • <=: 以下 (Less than or equal to)
  • 論理演算子:
    • and: 論理積 (Logical AND) - 両方の条件が真の場合に True を返す。
    • or: 論理和 (Logical OR) - いずれかの条件が真の場合に True を返す。
    • not: 否定 (Logical NOT) - 条件を反転させる (True なら False、False なら True)。

これらの演算子を組み合わせることで、より複雑な条件式を作成できます。例えば、x > 5 and y < 10 は、「x が 5 より大きく、かつ y が 10 より小さい」という条件を表します。

Explanation in English:

A Boolean expression, used in conditional branching, is an expression that evaluates to either True or False. Examples include x > 5 and y == 10. Python evaluates these expressions and branches the execution flow based on their results.

Here are common comparison operators and logical operators used in Python:

  • Comparison Operators:
    • ==: Equal to
    • !=: Not equal to
    • >: Greater than
    • <: Less than
    • >=: Greater than or equal to
    • <=: Less than or equal to
  • Logical Operators:
    • and: Logical AND - Returns True if both conditions are True.
    • or: Logical OR - Returns True if either condition is True.
    • not: Logical NOT - Inverts the condition (True becomes False, and False becomes True).

By combining these operators, you can create more complex Boolean expressions. For example, x > 5 and y < 10 represents the condition "x is greater than 5 AND y is less than 10."

3. 練習問題と解説 (1~10)

それでは、条件分岐の理解を深めるための練習問題を10問取り組んでいきましょう。各問題には、解答例と解説が含まれていますので、参考にしながら挑戦してみてください。

問題 1: 偶数・奇数の判定

整数を入力として受け取り、それが偶数か奇数かを判定するプログラムを作成してください。

num = int(input("整数を入力してください: "))
if num % 2 == 0:
    print(f"{num} は偶数です")
else:
    print(f"{num} は奇数です")

解説: 入力された整数 num を 2 で割った余りが 0 ならば偶数、そうでなければ奇数と判定します。% は剰余演算子で、割り算の余りを返します。

Explanation in English:

Write a program that takes an integer as input and determines whether it is even or odd.

num = int(input("Enter an integer: "))
if num % 2 == 0:
    print(f"{num} is even.")
else:
    print(f"{num} is odd.")

Explanation: The program checks if the input integer num divided by 2 has a remainder of 0. If it does, the number is even; otherwise, it's odd. The % operator (modulo) returns the remainder of a division.

問題 2: 3の倍数の判定

整数を入力として受け取り、それが3の倍数かどうかを判定するプログラムを作成してください。

num = int(input("整数を入力してください: "))
if num % 3 == 0:
    print(f"{num} は3の倍数です")
else:
    print(f"{num} は3の倍数ではありません")

解説: 問題1と同様に、剰余演算子 % を使用して判定します。

Explanation in English:

Write a program that takes an integer as input and determines whether it is a multiple of 3.

num = int(input("Enter an integer: "))
if num % 3 == 0:
    print(f"{num} is a multiple of 3.")
else:
    print(f"{num} is not a multiple of 3.")

Explanation: Similar to problem 1, the program uses the modulo operator % to check if the input integer num is divisible by 3.

問題 3: 年齢によるメッセージ表示

年齢を入力として受け取り、20歳以上の場合は「成人です」、それ以下の場合は「未成年です」と表示するプログラムを作成してください。

age = int(input("年齢を入力してください: "))
if age >= 20:
    print("成人です")
else:
    print("未成年です")

解説: age が 20 以上であれば「成人です」、そうでなければ「未成年です」と表示します。

Explanation in English:

Write a program that takes an age as input and displays "Adult" if the age is 20 or older, and "Minor" otherwise.

age = int(input("Enter your age: "))
if age >= 20:
    print("Adult")
else:
    print("Minor")

Explanation: The program checks if age is greater than or equal to 20. If it is, it prints "Adult"; otherwise, it prints "Minor."

問題 4: グレード判定

試験の点数を入力として受け取り、以下の条件でグレードを判定するプログラムを作成してください。

  • 90点以上: A
  • 80点以上: B
  • 70点以上: C
  • 60点以上: D
  • それ以下: F
score = int(input("試験の点数を入力してください: "))
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
elif score >= 60:
    print("D")
else:
    print("F")

解説: if-elif-else 文を使用して、点数に応じて適切なグレードを表示します。

Explanation in English:

Write a program that takes an exam score as input and assigns a grade based on the following criteria:

  • 90 or above: A
  • 80 to 89: B
  • 70 to 79: C
  • 60 to 69: D
  • Below 60: F
score = int(input("Enter your exam score: "))
if score >= 90:
    print("A")
elif score >= 80:
    print("B")
elif score >= 70:
    print("C")
elif score >= 60:
    print("D")
else:
    print("F")

Explanation: The program uses an if-elif-else statement to determine the appropriate grade based on the input score. The elif statements are checked sequentially only if the preceding conditions were false.

問題 5: 2つの数値の大小比較

2つの整数を入力として受け取り、大きい方の値を表示するプログラムを作成してください。

num1 = int(input("最初の整数を入力してください: "))
num2 = int(input("次の整数を入力してください: "))
if num1 > num2:
    print(f"大きい方は {num1} です")
elif num2 > num1:
    print(f"大きい方は {num2} です")
else:
    print("2つの数値は等しいです")

解説: if-elif 文を使用して、2つの数値の大小を比較し、大きい方の値を表示します。等しい場合は、その旨を表示します。

Explanation in English:

Write a program that takes two integers as input and displays the larger of the two.

num1 = int(input("Enter the first integer: "))
num2 = int(input("Enter the second integer: "))
if num1 > num2:
    print(f"The larger number is {num1}")
elif num2 > num1:
    print(f"The larger number is {num2}")
else:
    print("The two numbers are equal.")

Explanation: The program uses an if-elif statement to compare the two input integers and display the larger one. If they are equal, it prints a message indicating that they are equal.

問題 6: うるう年の判定

西暦を入力として受け取り、それがうるう年かどうかを判定するプログラムを作成してください。うるう年は、4で割り切れるが100で割り切れず、または400で割り切れる年です。

year = int(input("西暦を入力してください: "))
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
    print(f"{year} はうるう年です")
else:
    print(f"{year} はうるう年ではありません")

解説: うるう年の条件を andor を使用して表現しています。

Explanation in English:

Write a program that takes a year as input and determines whether it is a leap year. A leap year is divisible by 4, but not by 100, unless it is also divisible by 400.

year = int(input("Enter the year: "))
if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
    print(f"{year} is a leap year.")
else:
    print(f"{year} is not a leap year.")

Explanation: The program uses the modulo operator % and logical operators and and or to check if the input year meets the criteria for a leap year. The condition (year % 4 == 0 and year % 100 != 0) or year % 400 == 0 accurately reflects the definition of a leap year.

問題 7: BMIの計算と判定

身長 (cm) と体重 (kg) を入力として受け取り、BMI (Body Mass Index) を計算し、以下の条件で肥満度を判定するプログラムを作成してください。

  • 18.5未満: 低体重
  • 18.5以上25未満: 標準体重
  • 25以上30未満: 過体重
  • 30以上: 肥満
height = float(input("身長 (cm) を入力してください: "))
weight = float(input("体重 (kg) を入力してください: "))
bmi = weight / ((height / 100) ** 2)
if bmi < 18.5:
    print("低体重")
elif bmi < 25:
    print("標準体重")
elif bmi < 30:
    print("過体重")
else:
    print("肥満")

解説: BMIの計算式を用いてBMIを計算し、if-elif-else 文を使用して肥満度を判定します。

Explanation in English:

Write a program that takes height (in cm) and weight (in kg) as input, calculates the Body Mass Index (BMI), and determines the degree of obesity based on the following criteria:

  • Less than 18.5: Underweight
  • 18.5 to 24.9: Normal weight
  • 25 to 29.9: Overweight
  • 30 or greater: Obese
height = float(input("Enter your height (cm): "))
weight = float(input("Enter your weight (kg): "))
bmi = weight / ((height / 100) ** 2)
if bmi < 18.5:
    print("Underweight")
elif bmi < 25:
    print("Normal weight")
elif bmi < 30:
    print("Overweight")
else:
    print("Obese")

Explanation: The program calculates the BMI using the formula weight / ((height / 100) ** 2) and then uses an if-elif-else statement to determine the appropriate category based on the calculated BMI. Note that the upper bound for "Normal weight" is 24.9, not 25.

問題 8: 複数の条件による判定 (論理演算子)

年齢と性別を入力として受け取り、以下の条件を満たす場合に「対象者です」と表示するプログラムを作成してください。

  • 20歳以上
  • 男性
age = int(input("年齢を入力してください: "))
gender = input("性別 (男/女) を入力してください: ")
if age >= 20 and gender == "男":
    print("対象者です")
else:
    print("対象者ではありません")

解説: and 演算子を使用して、年齢と性別の両方の条件を満たすかどうかを判定します。

Explanation in English:

Write a program that takes age and gender as input and displays "Eligible" if the following conditions are met:

  • Age is 20 or older
  • Gender is male
age = int(input("Enter your age: "))
gender = input("Enter your gender (male/female): ")
if age >= 20 and gender == "男":
    print("Eligible")
else:
    print("Not eligible")

Explanation: The program uses the and logical operator to check if both conditions (age is 20 or older AND gender is male) are true. The input for gender should be in Japanese "男" for this code to work correctly.

問題 9: ネストされたif文

ある商品の価格を入力として受け取り、以下の条件で割引額を計算し表示するプログラムを作成してください。

  • 10,000円以上の場合:5%の割引
  • 5,000円以上10,000円未満の場合:3%の割引
  • それ以下の場合:割引なし
price = float(input("商品の価格を入力してください: "))
if price >= 10000:
    discount = price * 0.05
    print(f"割引額は {discount} 円です")
elif price >= 5000:
    discount = price * 0.03
    print(f"割引額は {discount} 円です")
else:
    print("割引なし")

解説: ネストされた if-elif 文を使用して、価格帯に応じて割引額を計算します。

Explanation in English:

Write a program that takes the price of an item as input and calculates the discount amount based on the following criteria:

  • 10,000 or more: 5% discount
  • 5,000 to 9,999: 3% discount
  • Below 5,000: No discount
price = float(input("Enter the price of the item: "))
if price >= 10000:
    discount = price * 0.05
    print(f"The discount amount is {discount} yen")
elif price >= 5000:
    discount = price * 0.03
    print(f"The discount amount is {discount} yen")
else:
    print("No discount")

Explanation: The program uses nested if-elif statements to determine the appropriate discount based on the input price. This demonstrates how to use multiple conditional checks in a structured way.

問題 10: 三項演算子 (条件式)

ある数値が正の数、負の数、またはゼロかを判定し、それぞれ「正の数」、「負の数」、「ゼロ」と表示するプログラムを作成してください。三項演算子を使用してください。

num = float(input("数値を入力してください: "))
result = "正の数" if num > 0 else ("負の数" if num < 0 else "ゼロ")
print(result)

解説: 三項演算子 ( value_if_true if condition else value_if_false ) を使用して、簡潔に判定結果を表示します。

Explanation in English:

Write a program that takes a number as input and displays "Positive" if the number is positive, "Negative" if it's negative, or "Zero" if it's zero. Use the ternary operator.

num = float(input("Enter a number: "))
result = "Positive" if num > 0 else ("Negative" if num < 0 else "Zero")
print(result)

Explanation: The program uses the ternary operator to concisely determine and display the result based on whether the input number is positive, negative, or zero. The nested ternary operator provides a compact way to express this logic.

4. まとめとさらなる学習

本記事では、Pythonの条件分岐について、基本的な構文から応用的なテクニックまで幅広く解説しました。これらの練習問題を解くことで、条件分岐の概念を深く理解し、より複雑なプログラムを作成できるようになるはずです。

さらなる学習:

  • switch-case 文の代替: Pythonには switch-case 文のような構文は直接ありませんが、辞書 (dictionary) を使用することで同様の処理を実現できます。
  • 真理値テスト: Pythonでは、様々な型が真偽値を持ちます。例えば、空のリストや文字列は False と評価され、それ以外の値は True と評価されます。これを利用して、より簡潔な条件式を作成できます。
  • 複雑な条件式の可読性: 複雑な条件式は可読性を低下させる可能性があります。必要に応じて、中間変数を使用したり、関数に分割するなどして、コードを整理することを心がけましょう。

Pythonの条件分岐は、プログラム開発において非常に重要なスキルです。本記事で学んだ知識を活かして、様々な問題に挑戦し、プログラミング能力を高めてください。