0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

四則演算の自動生成プログラム

Last updated at Posted at 2023-02-20

はじめに

python3でつくってみました

要件

  • 1問1答形式の四則演算の生成する
  • 開始直後に問題数を入力させる
  • 全ての問題への回答が完了したら、正解数を出力する

実行例

問題数を入力してください: 5
1. 69 - 28 = 41
2. 4 * 10 = 40
3. 72 - 10 = 62
4. 9 / 9 = 1.0
5. 3 * 3 = 9

正解数は 5 / 5 です。

スクリプト

sansuu.py
import random

# 四則演算の問題を生成する関数
def generate_question():
    operator = random.choice(["+", "-", "*", "/"])
    if operator == "+":
        num1 = random.randint(1, 100)
        num2 = random.randint(1, 100)
        answer = num1 + num2
    elif operator == "-":
        num1 = random.randint(1, 100)
        num2 = random.randint(1, num1)
        answer = num1 - num2
    elif operator == "*":
        num1 = random.randint(1, 10)
        num2 = random.randint(1, 10)
        answer = num1 * num2
    elif operator == "/":
        num2 = random.randint(1, 10)
        num1 = num2 * random.randint(1, 10)
        answer = num1 / num2
    return f"{num1} {operator} {num2}", answer

# メイン関数
def main():
    # 問題数の入力
    num_questions = int(input("問題数を入力してください: "))
    
    # 問題の生成
    questions = []
    answers = []
    for i in range(num_questions):
        question, answer = generate_question()
        questions.append(question)
        answers.append(answer)

    # 回答の入力と検証
    num_correct = 0
    for i in range(num_questions):
        print(f"{i+1}. {questions[i]} = ", end="")
        user_answer = input()
        if float(user_answer) == answers[i]:
            num_correct += 1

    # 正解数の出力
    print(f"\n正解数は {num_correct} / {num_questions} です。")

if __name__ == "__main__":
    main()
0
0
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?