一、功能要求: (1)用文件保存试题库。(每个试题包括题干、4个备选答案、标准答案) (2)试题录入:可随时增加试题到试题库中 (3)试题抽取:每次从试题库中可以随机抽出N道题(N由键盘输入) (4)答题:用户可实现输入自
时间: 2024-02-03 16:15:13 浏览: 142
己答案,并得到本次测试的得分和正确率。
二、实现思路:
1. 文件保存试题库。可以使用csv文件格式,每行记录一道试题,包括题干、4个备选答案、标准答案,用逗号分隔。
2. 试题录入。可以通过程序提示用户输入题干、备选答案和标准答案,将数据保存到csv文件中。
3. 试题抽取。可以使用random模块的sample函数实现从csv文件中随机抽取N道题。
4. 答题。程序随机抽取N道题并显示给用户,用户输入答案后,程序计算出得分和正确率。
三、代码实现:
1. 文件保存试题库:
```python
import csv
# 将试题保存到csv文件中
def save_question(question):
with open('question.csv', 'a', newline='') as f:
writer = csv.writer(f)
writer.writerow(question)
```
2. 试题录入:
```python
# 录入试题
def input_question():
question = []
question.append(input('请输入题干:'))
for i in range(4):
question.append(input('请输入备选答案{}:'.format(i+1)))
question.append(input('请输入标准答案:'))
save_question(question)
```
3. 试题抽取:
```python
import random
# 从csv文件中抽取N道题
def get_questions(n):
questions = []
with open('question.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
questions.append(row)
return random.sample(questions, n)
```
4. 答题:
```python
# 答题
def answer_questions():
n = int(input('请输入题目数量:'))
questions = get_questions(n)
score = 0
for q in questions:
print(q[0])
for i in range(4):
print('{}、{}'.format(i+1, q[i+1]))
answer = input('请输入答案编号:')
if answer == q[5]:
score += 1
print('得分:{},正确率:{}'.format(score, score/n))
```
四、完整代码:
```python
import csv
import random
# 将试题保存到csv文件中
def save_question(question):
with open('question.csv', 'a', newline='') as f:
writer = csv.writer(f)
writer.writerow(question)
# 录入试题
def input_question():
question = []
question.append(input('请输入题干:'))
for i in range(4):
question.append(input('请输入备选答案{}:'.format(i+1)))
question.append(input('请输入标准答案:'))
save_question(question)
# 从csv文件中抽取N道题
def get_questions(n):
questions = []
with open('question.csv', 'r') as f:
reader = csv.reader(f)
for row in reader:
questions.append(row)
return random.sample(questions, n)
# 答题
def answer_questions():
n = int(input('请输入题目数量:'))
questions = get_questions(n)
score = 0
for q in questions:
print(q[0])
for i in range(4):
print('{}、{}'.format(i+1, q[i+1]))
answer = input('请输入答案编号:')
if answer == q[5]:
score += 1
print('得分:{},正确率:{}'.format(score, score/n))
# 主程序
def main():
while True:
print('1. 录入试题')
print('2. 答题')
print('3. 退出')
choice = input('请选择操作:')
if choice == '1':
input_question()
elif choice == '2':
answer_questions()
elif choice == '3':
break
else:
print('无效操作,请重新选择!')
if __name__ == '__main__':
main()
```
阅读全文