ななぶろ

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

Pythonプログラム練習問題10選:ループを活用してステップアップ!

www.amazon.co.jp

Python プログラム練習問題 10 選:ループを活用してステップアップ!

Python は、そのシンプルさと汎用性から、初心者からプロフェッショナルまで幅広い層に利用されている人気のプログラミング言語です。特に、繰り返し処理を行うための ループ は、プログラムの効率性と可読性を高める上で非常に重要な概念です。

この記事では、Python のループ(for ループと while ループ)を効果的に活用するための練習問題 10 選を紹介します。各問題には、問題文、ヒント、そして解決策のコード例と解説が含まれています。これらの問題を解くことで、あなたの Python プログラミングスキルは確実に向上するでしょう。

1. ループとは? - 基本概念を理解しよう

まず、ループとは何か、なぜ必要なのかを簡単に説明します。

ループ とは、プログラム内の同じコードブロックを繰り返し実行するための構文です。例えば、リストのすべての要素に対して処理を行いたい場合や、特定の条件が満たされるまで処理を繰り返したい場合に役立ちます。 ループを使用することで、冗長なコードを避け、プログラムをより簡潔で効率的にすることができます。

Python には主に 2 つの種類のループがあります。

  • for ループ: シーケンス(リスト、タプル、文字列など)の各要素に対して処理を行います。
  • while ループ: 指定された条件が真である限り、コードブロックを繰り返し実行します。

Explanation in English:

A loop is a programming construct that allows you to execute a block of code repeatedly. This is essential for tasks like processing every element in a list or continuing an operation until a specific condition is met. Loops improve efficiency and readability by avoiding redundant code. Python offers two main types of loops:

  • for loop: Iterates over each item in a sequence (list, tuple, string, etc.).
  • while loop: Executes a block of code as long as a given condition is true.

2. 練習問題 1: for ループでリストの要素を出力する

問題: 次のリストの要素を順番に出力してください。

my_list = ["apple", "banana", "cherry"]

ヒント: for ループを使って、リストの各要素にアクセスし、print() 関数で出力します。

解決策:

my_list = ["apple", "banana", "cherry"]

for fruit in my_list:
    print(fruit)

解説: for fruit in my_list: は、my_list の各要素を順番に fruit という変数に代入し、ループ内のコードを実行します。 print(fruit) は、現在の fruit の値を画面に出力します。 この例では、リストの各文字列("apple", "banana", "cherry")が順番に fruit 変数に割り当てられ、それぞれが出力されます。

Explanation in English:

Problem: Print each element of the following list sequentially.

my_list = ["apple", "banana", "cherry"]

Hint: Use a for loop to access each item in the list and use the print() function to output it.

Solution:

my_list = ["apple", "banana", "cherry"]

for fruit in my_list:
    print(fruit)

Explanation: The line for fruit in my_list: iterates through each element of the list my_list. In each iteration, the current element is assigned to the variable fruit. The print(fruit) statement then displays the value of fruit on the screen. This results in "apple", "banana", and "cherry" being printed one after another.

3. 練習問題 2: while ループでカウントアップ

問題: 0 から 4 までの数字を順番に出力してください。

ヒント: while ループとカウンタ変数を使用します。カウンタ変数を初期化し、ループ内でインクリメント(増加)させます。

解決策:

count = 0

while count <= 4:
    print(count)
    count += 1

解説: count = 0 は、カウンタ変数を初期化します。 while count <= 4: は、count が 5 より小さい間、ループ内のコードを実行します。 print(count) は、現在の count の値を画面に出力します。 count += 1 は、count を 1 増やします。 このループは、count が 0, 1, 2, 3, 4 と順番に増加し、それぞれの値が出力されます。 count が 5 になると、条件 count <= 4 が偽になり、ループが終了します。

Explanation in English:

Problem: Print the numbers from 0 to 4 sequentially.

Hint: Use a while loop and a counter variable. Initialize the counter variable and increment it within the loop.

Solution:

count = 0

while count <= 4:
    print(count)
    count += 1

Explanation: The line count = 0 initializes a counter variable named count. The while count <= 4: statement continues the loop as long as the value of count is less than or equal to 4. Inside the loop, print(count) displays the current value of count, and count += 1 increments count by 1 in each iteration. The loop executes until count becomes 5, at which point the condition count <= 4 is no longer true, and the loop terminates.

4. 練習問題 3: リストの要素の合計を計算する

問題: 次のリストの要素の合計を計算してください。

numbers = [1, 2, 3, 4, 5]

ヒント: for ループを使って、リストの各要素にアクセスし、変数に加算します。

解決策:

numbers = [1, 2, 3, 4, 5]
total = 0

for number in numbers:
    total += number

print(total)  # 出力: 15

解説: total = 0 は、合計を格納する変数を初期化します。 for number in numbers: は、リストの各要素を順番に number という変数に代入し、ループ内のコードを実行します。 total += number は、現在の number の値を total に加算します。 このループは、リストのすべての要素が total に加算されるまで繰り返されます。 最後に、print(total) で計算された合計が表示されます。

Explanation in English:

Problem: Calculate the sum of the elements in the following list.

numbers = [1, 2, 3, 4, 5]

Hint: Use a for loop to access each element in the list and add it to a variable.

Solution:

numbers = [1, 2, 3, 4, 5]
total = 0

for number in numbers:
    total += number

print(total)  # Output: 15

Explanation: The line total = 0 initializes a variable named total to store the sum. The for number in numbers: statement iterates through each element of the list numbers, assigning each element to the variable number. Inside the loop, total += number adds the current value of number to the total. After iterating through all elements, print(total) displays the calculated sum (15).

5. 練習問題 4: 文字列の反転

問題: 次の文字列を反転させてください。

text = "hello"

ヒント: for ループを使って、文字列の各文字にアクセスし、新しい文字列に追加します。ただし、文字は逆順に追加する必要があります。

解決策:

text = "hello"
reversed_text = ""

for i in range(len(text) - 1, -1, -1):
    reversed_text += text[i]

print(reversed_text)  # 出力: olleh

解説: range(len(text) - 1, -1, -1) は、文字列のインデックスを逆順に生成します。 len(text) は文字列の長さを返します。 len(text) - 1 は最後の文字のインデックスです。 -1 はループが終了するインデックス(含まない)です。 -1 はステップ値で、インデックスを 1 つずつ減らします。 text[i] は、i 番目の文字を取得します。 reversed_text += text[i] は、取得した文字を reversed_text に追加します。 このループは、文字列の最後の文字から最初の文字まで逆順に処理し、反転された文字列を構築します。

Explanation in English:

Problem: Reverse the following string.

text = "hello"

Hint: Use a for loop to access each character of the string and add it to a new string. However, you need to add the characters in reverse order.

Solution:

text = "hello"
reversed_text = ""

for i in range(len(text) - 1, -1, -1):
    reversed_text += text[i]

print(reversed_text)  # Output: olleh

Explanation: The line range(len(text) - 1, -1, -1) generates a sequence of indices from the last character's index (length of the string minus 1) down to 0, decrementing by 1 in each step. text[i] retrieves the character at index i. The line reversed_text += text[i] appends the retrieved character to the reversed_text string. This loop iterates through the string from right to left, building up the reversed string.

6. 練習問題 5: FizzBuzz 問題

問題: 1 から 100 までの数字を順番に出力してください。ただし、3 の倍数の場合は "Fizz"、5 の倍数の場合は "Buzz"、両方の倍数の場合は "FizzBuzz" と出力してください。

ヒント: for ループと if-elif-else 文を使用します。

解決策:

for i in range(1, 101):
    if i % 3 == 0 and i % 5 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

解説: i % 3 == 0 は、i が 3 で割り切れるかどうかをチェックします。 i % 5 == 0 は、i が 5 で割り切れるかどうかをチェックします。 if-elif-else 文を使って、条件に応じて適切な文字列を出力します。 and 演算子を使用することで、3 と 5 の両方の倍数である場合に "FizzBuzz" を出力できます。

Explanation in English:

Problem: Print the numbers from 1 to 100 sequentially. However, if a number is divisible by 3, print "Fizz"; if it's divisible by 5, print "Buzz"; and if it's divisible by both 3 and 5, print "FizzBuzz".

Hint: Use a for loop and an if-elif-else statement.

Solution:

for i in range(1, 101):
    if i % 3 == 0 and i % 5 == 0:
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)

Explanation: The for loop iterates through numbers from 1 to 100. The if i % 3 == 0 and i % 5 == 0: statement checks if the number is divisible by both 3 and 5 (using the modulo operator %). If it is, "FizzBuzz" is printed. The elif i % 3 == 0: statement checks for divisibility by 3 only, printing "Fizz". The elif i % 5 == 0: statement checks for divisibility by 5 only, printing "Buzz". Finally, the else block prints the number itself if it's not divisible by either 3 or 5.

7. 練習問題 6: 九九の表を表示する

問題: 九九の表(1 から 9 まで)を縦横に表示してください。

ヒント: ネストされた for ループを使用します。外側のループは段数を、内側のループは単数を繰り返します。

解決策:

for i in range(1, 10):
    for j in range(1, 10):
        print(i * j, end="\t")  # タブで区切って表示
    print()  # 改行

解説: 外側のループ for i in range(1, 10): は、段数を 1 から 9 まで繰り返します。 内側のループ for j in range(1, 10): は、単数を 1 から 9 まで繰り返します。 print(i * j, end="\t") は、ij の積をタブで区切って表示します。 end="\t" は、改行せずにタブで次の出力を区切るように指示します。 print() は、各段の最後に改行を出力します。

Explanation in English:

Problem: Display the multiplication table (from 1 to 9) vertically and horizontally.

Hint: Use nested for loops. The outer loop iterates through rows, and the inner loop iterates through columns.

Solution:

for i in range(1, 10):
    for j in range(1, 10):
        print(i * j, end="\t")  # Display with a tab separator
    print()  # Newline

Explanation: The outer loop for i in range(1, 10): iterates through the rows (from 1 to 9). The inner loop for j in range(1, 10): iterates through the columns (from 1 to 9). print(i * j, end="\t") prints the product of i and j, followed by a tab character (\t) to separate the numbers. The end="\t" argument prevents a newline after each number. print() without any arguments is used to print a newline at the end of each row.

8. 練習問題 7: リストから偶数のみ抽出する

問題: 次のリストから偶数のみを抽出し、新しいリストとして格納してください。

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

ヒント: for ループと if 文を使用します。

解決策:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []

for number in numbers:
    if number % 2 == 0:
        even_numbers.append(number)

print(even_numbers)  # Output: [2, 4, 6, 8, 10]

解説: total = 0 は、合計を格納する変数を初期化します。 for number in numbers: は、リストの各要素を順番に number という変数に代入し、ループ内のコードを実行します。 print(fruit) は、現在の fruit の値を画面に出力します。

Explanation in English:

Problem: Extract only the even numbers from the following list and store them in a new list.

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

Hint: Use a for loop and an if statement.

Solution:

numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
even_numbers = []

for number in numbers:
    if number % 2 == 0:
        even_numbers.append(number)

print(even_numbers)  # Output: [2, 4, 6, 8, 10]

Explanation: even_numbers = [] initializes an empty list to store the even numbers. The for number in numbers: loop iterates through each element of the numbers list. Inside the loop, if number % 2 == 0: checks if the current number is even (divisible by 2 with no remainder). If it's even, even_numbers.append(number) adds the number to the even_numbers list.

9. 練習問題 8: while ループでユーザー入力を受け付ける

問題: ユーザーに数字を入力させ、入力された数字が正の整数である限り、その数字を画面に出力し続けるプログラムを作成してください。ユーザーが負の数または 0 を入力した場合、ループを終了します。

ヒント: while ループと input() 関数を使用します。 try-except ブロックでエラー処理を行います。

解決策:

while True:
    try:
        number = int(input("正の整数を入力してください (負の数または 0 を入力すると終了します): "))
        if number <= 0:
            break  # ループを終了
        print(number)
    except ValueError:
        print("無効な入力です。数字を入力してください。")

解説: while True: は、無限ループを作成します。 input() 関数は、ユーザーからの入力を文字列として受け取ります。 int() 関数は、文字列を整数に変換します。 try-except ブロックで、数値への変換が失敗した場合のエラー処理を行います。 if number <= 0: は、入力された数字が負の数または 0 であるかどうかをチェックし、その場合は break 文でループを終了します。

Explanation in English:

Problem: Create a program that prompts the user to enter numbers and continues printing those numbers to the screen as long as they are positive integers. The loop should terminate when the user enters a negative number or 0.

Hint: Use a while loop and the input() function. Use a try-except block for error handling.

Solution:

while True:
    try:
        number = int(input("Enter a positive integer (enter a negative number or 0 to exit): "))
        if number <= 0:
            break  # Exit the loop
        print(number)
    except ValueError:
        print("Invalid input. Please enter a number.")

Explanation: The while True: statement creates an infinite loop. The input() function prompts the user to enter a number and returns it as a string. The int() function attempts to convert the string input into an integer. The try-except block handles potential errors that might occur if the user enters non-numeric input (e.g., letters or symbols). If a ValueError occurs during the conversion, the except block prints an error message. The if number <= 0: statement checks if the entered number is negative or zero. If it is, the break statement exits the loop. Otherwise, the print(number) statement displays the positive integer that was entered.

10. 練習問題 9: リスト内包表記 (List Comprehension) を使って偶数のリストを作成する

問題: リスト内包表記を使って、1 から 20 までの数字のリストから偶数のみを含む新しいリストを作成してください。

ヒント: リスト内包表記は、ループと条件式を簡潔に記述できる強力な機能です。

解決策:

even_numbers = [number for number in range(1, 21) if number % 2 == 0]
print(even_numbers)  # Output: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

解説: [number for number in range(1, 21) if number % 2 == 0] は、リスト内包表記です。 for number in range(1, 21) は、1 から 20 までの数字を順番に number という変数に代入します。 if number % 2 == 0 は、number が偶数であるかどうかをチェックします。 偶数の場合のみ、number が新しいリストに追加されます。

Explanation in English:

Problem: Use list comprehension to create a new list containing only the even numbers from a list of numbers from 1 to 20.

Hint: List comprehensions are a powerful feature that allows you to write loops and conditional statements concisely.

Solution:

even_numbers = [number for number in range(1, 21) if number % 2 == 0]
print(even_numbers)  # Output: [2, 4, 6, 8, 10, 12, 14, 16, 18, 20]

Explanation: The [number for number in range(1, 21) if number % 2 == 0] is a list comprehension. for number in range(1, 21) iterates through the numbers from 1 to 20, assigning each number to the variable number. if number % 2 == 0 checks if the current number is even (divisible by 2 with no remainder). Only even numbers are included in the new list.

まとめ

この記事では、Python のループ(for ループと while ループ)を活用するための練習問題 10 選を紹介しました。これらの問題を解くことで、あなたの Python プログラミングスキルは確実に向上するでしょう。 また、リスト内包表記のような簡潔なコード記述方法も学ぶことができました。

ループは、Python プログラミングにおいて非常に重要な概念です。様々な問題を解決するために、積極的に活用してみてください。さらに深く学びたい場合は、以下のリソースを参照してください。

これらの練習問題とリソースを活用して、Python プログラミングのスキルをさらに向上させてください!