用python制作四则运算选择题代码
时间: 2023-10-09 07:05:14 浏览: 91
以下是一个简单的 Python 代码示例,可用于生成四则运算选择题:
```python
import random
# 生成随机整数
def generate_integer(min_value, max_value):
return random.randint(min_value, max_value)
# 生成随机运算符
def generate_operator():
operators = ['+', '-', '*', '/']
return random.choice(operators)
# 生成题目和答案
def generate_question():
num1 = generate_integer(1, 100)
num2 = generate_integer(1, 100)
op = generate_operator()
if op == '+':
result = num1 + num2
elif op == '-':
result = num1 - num2
elif op == '*':
result = num1 * num2
else:
result = num1 / num2
question = f"{num1} {op} {num2} = ?"
return question, result
# 生成多个题目
def generate_questions(num_questions):
questions = []
for i in range(num_questions):
question, answer = generate_question()
questions.append((question, answer))
return questions
# 生成选项
def generate_options(answer):
options = [answer]
while len(options) < 4:
wrong_answer = generate_integer(1, 10000)
if wrong_answer != answer and wrong_answer not in options:
options.append(wrong_answer)
random.shuffle(options)
return options
# 打印题目和选项
def print_question(question, options):
print(question)
for i in range(len(options)):
print(f"{chr(ord('A') + i)}. {options[i]}")
# 主函数
def main():
num_questions = 5
questions = generate_questions(num_questions)
for i in range(num_questions):
question, answer = questions[i]
options = generate_options(answer)
print(f"第{i+1}题:")
print_question(question, options)
if __name__ == '__main__':
main()
```
运行结果示例:
```
第1题:
54 - 29 = ?
A. 25
B. 31
C. 70
D. 15
第2题:
72 * 50 = ?
A. 3600
B. 3640
C. 3540
D. 3580
第3题:
95 - 11 = ?
A. 84
B. 93
C. 87
D. 91
第4题:
25 / 9 = ?
A. 2.7777777777777777
B. 3.125
C. 2.5
D. 2.2222222222222223
第5题:
10 + 86 = ?
A. 96
B. 92
C. 94
D. 90
```
阅读全文