小学老师要每周给同学出300道四则运算练习题。
要求:
1.两个运算符;
2.100以内的数字;
3.需要写答案,并且保证答案在0...100之间;
解题思路:
1.构建一个类专门用于产生练习题
2.类中的方法分别为产生数字的方法,产生运算符的方法以及检验是否在规定数据范围内的方法。
代码如下:
1 import random 2 3 4 operator = ['+', '-', '*', '/'] 5 6 7 class testCal: 8 def __init__(self, limit): #limit 数据范围 9 self.limit = limit 10 def createNum(self): #产生数字 11 a = random.randint(0, 1) 12 if a == 0: 13 opt = round(random.uniform(1, self.limit), 0) 14 else: 15 opt = round(random.uniform(1, self.limit), 2) 16 return opt 17 def createOperator(self): #产生操作符 18 return random.choice(operator) 19 20 def check(self): #判断是否在数据范围内 21 opr = self.createOperator() 22 opt1 = self.createNum() 23 opt2 = self.createNum() 24 self.opt1 = opt1 25 self.opt2 = opt2 26 self.opr = opr 27 if opr == '*' and opt1 * opt2 <= 100: 28 self.ans = round(self.opt1 * self.opt2,2) 29 elif opr == '/' and opt1 / opt2 <= 100: 30 self.ans = round(self.opt1 / self.opt2,2) 31 elif opr == '+' and opt1 + opt2 <= 100: 32 self.ans = round(self.opt1 + self.opt2,2) 33 elif opr == '-' and opt1 - opt1 <= 100: 34 self.ans = round(self.opt1 - self.opt2,2) 35 else: 36 return False 37 return True 38 39 def getCal(self): #输出计算式,并返回答案 40 while self.check(): 41 print(self.opt1, self.opr, self.opt2, end='') 42 self.userAns = int(input('=')) 43 break 44 return self.ans, self.userAns 45 46 47 if __name__ == '__main__': 48 count, limit = map(int, input("请输入题数和数据的范围:").split()) 49 cal = testCal(limit) 50 k = 1 51 while k <= count: 52 ans, userAns = cal.getCal() 53 if ans == userAns: 54 print("回答正确") 55 else: 56 print("错误,正确答案为:", ans) 57 k += 1
运行结果如下: