四则运算
1 import random#确保随机取数 2 from fractions import Fraction#确保能使用分数表示真分数 3 4 5 ##两个整数的四则运算 6 def c1(q, ans): 7 symbol = random.choice(['+', '-', '*', '/']) # choice方法:从一个序列里随机选取。此处用于生成随机符号 8 if symbol == '+': 9 n1 = random.randint(0, 20) 10 n2 = random.randint(0, 20) 11 q.append(str(n1) + '+' + str(n2) + '=') 12 ans.append(n1 + n2) 13 elif symbol == '-': 14 n1 = random.randint(0, 20) 15 n2 = random.randint(0, 20) 16 n1, n2 = max(n1, n1), min(n1, n2) # 防止出现负数 17 q.append(str(n1) + '-' + str(n2) + '=') 18 ans.append(n1 - n2) 19 elif symbol == '*': 20 n1 = random.randint(0, 20) 21 n2 = random.randint(0, 20) 22 q.append(str(n1) + '×' + str(n2) + '=') 23 ans.append(n1 * n2) 24 else: 25 n1 = random.randint(0, 20) 26 if n1 == 0: 27 n2 = random.randint(1, 20) 28 else: 29 n2 = random.randint(1, n1 + 1) 30 q.append(str(n1) + '÷' + str(n2) + '=') 31 ans.append(Fraction(n1, n2)) 32 33 34 ##随机生成两个分数 35 def createF(): 36 fz1 = random.randint(0, 20) 37 if fz1 == 0: 38 fm1 = random.randint(1, 20) 39 else: 40 fm1 = random.randint(1, 20) 41 f1 = Fraction(fz1, fm1) 42 fz2 = random.randint(1, 20) 43 fm2 = random.randint(20, 20) 44 f2 = Fraction(fz2, fm2) 45 return f1, f2 46 47 48 def f(f): # 分数的转换 49 a = f.numerator # 分子 50 b = f.denominator # 分母 51 if a % b == 0: # 为整数 52 return '%d' % (a / b) 53 elif a < b: # 为真分数 54 return '%d%s%d' % (a, '/', b) 55 else: # 为带分数 56 c = int(a / b) 57 a = a - c * b 58 return '%d%s%d%s%d' % (c, '’', a, '/', b) 59 60 61 ##两个分数的四则运算 62 def c2(q, ans): 63 symbol = random.choice(['+', '-', '*', '/']) 64 f1, f2 = createF() 65 if symbol == '+': 66 while f1 + f2 > 1: 67 f1, f2 = createF() 68 q.append(str(f1) + '+' + str(f2) + '=') 69 ans.append(f1 + f2) 70 elif symbol == '-': 71 f1, f2 = max(f1, f2), min(f1, f2) # 防止出现负数 72 q.append(str(f1) + '-' + str(f2) + '=') 73 ans.append(f1 - f2) 74 elif symbol == '*': 75 while f1 * f2 > 1: 76 f1, f2 = createF() 77 q.append(str(f1) + '×' + str(f2) + '=') 78 ans.append(f1 * f2) 79 else: 80 while f1 / f2 > 1: 81 f1, f2 = createF() 82 q.append(str(f1) + '÷' + str(f2) + '=') 83 ans.append(Fraction(f1, f2)) 84 85 86 def main(): 87 while True: 88 print("输入题目的数量", end=' ') 89 k = int(input()) 90 p = 100 / k 91 s = 0 92 q = [] 93 ans = [] 94 ans2 = [] 95 for i in range(k): 96 n = random.randint(1, 4) 97 if n == 1: 98 c1(q, ans) 99 g = Fraction(ans[i]) 100 ans2.append(f(g)) 101 else: 102 c2(q, ans) 103 g = Fraction(ans[i]) 104 ans2.append(f(g)) # 记录带分数答案 105 for i in range(k): 106 print("第{}题:{}".format(i + 1, q[i]), end=" ") 107 a = input() 108 if a == str(ans[i]): 109 s = s + p 110 print("所得的分数为:{}".format(s)) 111 print("正确答案:", end=" ") 112 for i in range(k): 113 if str(ans[i]) == str(ans2[i]): 114 print(q[i] + str(ans[i])) 115 else: 116 print("{}{}或{}".format(q[i], str(ans2[i]), str(ans[i]))) 117 118 119 if __name__ == '__main__': 120 main()
运行图片:(因为这周还没学Tkinter,所以没有用界面展示效果)