记一次python的小程序(大佬们莫来喷我)
程序员文章站
2022-04-21 23:26:24
...
最近在csdn看到一位博主用python写了个自动出两位数运算题目的程序,觉得挺有有意思的
于是自己就动手写了写(算是第一次用python写个程序吧),首先出题肯定是要能打印出来嘛,这个时候就需要安装docx第三方模块来对word进行操作
放出源码(希望大家看到能够给我提出些建议(不得不说python的大量内置函数节省了很多写算法的时间))
import random
import docx
import re
import time
#产生随机数字
def Number(m,n):
return str(random.randint(m,n))
#产生随机运算符号
def caculate_symbol():
symbol =['+','-','×','÷']
return str(random.choice(symbol))
#生成题目列表
def Test(target_two,target_three):
subject_all =[]
for i in range(0,target_three):
subject = ""
for x in range(0,target_two):
symbol = caculate_symbol()
subject +=(Number(k,j) + symbol)
subject = subject[0:-1] + "="
subject_all.append(subject)
return subject_all
#将答案保存在列表
def Answer(subject_all):
answer = []
for i in subject_all:
a = ""
c = re.sub('×',"*",i)
b = re.sub('÷',"/",c)
question = re.sub("=","",b)
a += i + str("%.1f" %(eval(question)))
answer.append(a)
return answer
#保存为题目
def Save_Test(subject_all):
doc = docx.Document()
doc.add_heading("加减乘除速算(答案保留1位小数)")
doc.add_paragraph('\n')
for i in subject_all:
doc.add_paragraph(i)
doc.save("速算试卷.docx")
print("\033[1;33;1m出题成功!\033[0m")
#保存答案
def Save_answer(answer):
doc = docx.Document()
doc.add_heading("加减乘除速算答案(答案保留一位小数)")
for i in answer:
doc.add_paragraph(i)
doc.save("速算试卷答案.docx")
print("\033[1;34;1m答案已给出!\033[0m","\033[1;31;1m题数为:%s个\033[0m" %len(answer))
#实现主要逻辑
def run():
try:
target_one = int(input("请输入运算数字的位数:"))
global j
j = 1
for i in range(0,target_one):
j *=10
global k
k = j // 10
target_two = int(input("请输入运算数字的个数:"))
target_three = int(input("请输入题数:"))
subject_all = Test(target_two,target_three)
Save_Test(subject_all)
answer = Answer(subject_all)
Save_answer(answer)
except:
print("\033[1;31;1m请按照提示正确输入!\033[0m")
if __name__ == '__main__':
while True:
run()
time.sleep(0.05)
quite = input("\033[1;31;1m按q键退出(任意键继续出题!)\033[0m")
if quite == 'q':
print("\033[1;36;1m已退出程序!\033[0m")
break
else:
print("\033[1;31;1m提示:继续出题会覆盖原来的题目\033[0m")
continue
展示下运行之后的结果,按提示输入:
将会在该python程序所在的文件夹里产生题目和题目答案的word文档
上一篇: 找到第K小的元素(分治)
下一篇: Linux:预处理、编译、汇编、链接