import random
def arithmetic_generator():
while True:
# 生成两个随机整数
num1 = random.randint(1, 10)
num2 = random.randint(1, 10)
# 选择是加法还是减法
operator = random.choice(['+', '-'])
# 生成题目和答案
if operator == '+':
question = f"{num1} {operator} {num2} = ?"
answer = num1 + num2
else:
question = f"{num1} {operator} {abs(num2)} = ?"
answer = num1 - num2 if num1 >= num2 else num2 - num1
yield question, answer
# 使用生成器
arithmetic_questions = arithmetic_generator()
# 获取并打印10个题目
for _ in range(10):
question, answer = next(arithmetic_questions)
print(question)
# 用户可以在这里输入答案并验证
user_answer = float(input("输入您的答案: ")) # 注意输入的可能是浮点数
if user_answer == answer:
print("正确!")
else:
print(f"错误!正确答案是: {answer}")
简便python的四则运算生成器代码
最新推荐文章于 2024-11-15 10:17:44 发布