自动生成四则运算题目

import random

def generate_math_questions(num_questions):
    questions = set()  # 使用集合来确保题目不重复
    while len(questions) < num_questions:
        num1 = random.randint(1, 30)
        num2 = random.randint(1, 30)
        operator = random.choice(['+', '-', '*', '/'])
        
        # 保证除法运算结果是整数
        if operator == '/':
            if num1 % num2 != 0:
                continue  # 重新生成题目
            answer = num1 // num2  # 使用整数除法以确保整数结果
        else:
            answer = eval(f"{num1} {operator} {num2}")  # 使用eval计算其他运算
        
        question = f"{num1} {operator} {num2} = ?"
        questions.add((question, answer))
    
    return list(questions)  # 转换为列表形式返回

num_questions = 20
questions = generate_math_questions(num_questions)

print("Here are your math questions:")
for i, (question, answer) in enumerate(questions, 1):
    print(f"Question {i}: {question}")

print("Now, let's check your answers.")

score = 0
for i, (question, answer) in enumerate(questions, 1):
    user_answer = input(f"Your answer for Question {i}: ")
    try:
        user_answer = int(user_answer)
    except ValueError:
        print(f"Invalid input! Please enter an integer.\n")
        continue
    
    if user_answer == answer:
        print("Correct!\n")
        score += 1
    else:
        print(f"Wrong! The correct answer is {answer}\n")

print(f"You answered {score} out of {num_questions} questions correctly.")

代码保证题目数量可选、确保题目不重复、

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值