[Python] A small program that randomly generates four arithmetic problems

import random
# 生成随机整数
def generate_random_number():
    return random.randint(1, 100)
# 生成随机运算符
def generate_random_operator():
    operators = ['+', '-', '*', '/']
    return random.choice(operators)
# 生成随机四则运算题目
def generate_math_question():
    num1 = generate_random_number()
    num2 = generate_random_number()
    operator = generate_random_operator()

    if operator == '/':
        # 除法运算,确保结果是整数
        num1 = num1 * num2
    elif operator == '-':
        # 减法运算,确保结果不为负数
        num1, num2 = max(num1, num2), min(num1, num2)

    question = f"{num1} {operator} {num2}"
    answer = eval(question)

    return question, answer

# 生成指定数量的四则运算题目
def generate_math_questions(num_questions):
    questions = []

    for _ in range(num_questions):
        question, answer = generate_math_question()
        questions.append((question, answer))

    return questions

# 示例用法
num_questions = 5  # 题目数量
questions = generate_math_questions(num_questions)

for i, (question, answer) in enumerate(questions, start=1):
    print(f"题目 {i}: {question} = ?")
    user_answer = int(input("你的答案: "))

    if user_answer == answer:
        print("回答正确!")
    else:
        print(f"错误,正确答案是: {answer}.")

This Python code implements a four-arithmetic arithmetic program with random questions. It contains the following functions:

1. `generate_random_number()`: Generate a random integer ranging from 1 to 100.
2. `generate_random_operator()`: Randomly select one of the four operators: addition, subtraction, multiplication and division.
3. `generate_math_question()`: Generate a random four-arithmetic question, including two random numbers and a random operator. Some adjustments are made to random numbers depending on the type of operator, such as ensuring that the result of division is an integer and avoiding negative results of subtraction.
4. `generate_math_questions(num_questions)`: Generate a specified number of random four arithmetic questions, use the `generate_math_question()` function to generate each question, and store the questions and answers in a list.
5. Example usage part: According to the set number of questions, generate random questions and display them to the user one by one, waiting for the user to enter the answer. Based on the comparison between the user's answer and the correct answer, the corresponding answer is given.

You can specify the number of questions `num_questions`, and the code will generate a corresponding number of random four-arithmetic arithmetic questions and display them to the user one by one. After the user enters the answer, the program will judge and give a prompt whether the answer is correct.

Guess you like

Origin blog.csdn.net/zhangawei123/article/details/130934361