#转自https://www.jianshu.com/c/00c61372c46a网址 #随机生成100以内的两个数字,实现随机的加减法。如果是减法,结果不能是负数。算错三次,给出正确答案 from random import randint,choice def add(x,y): return x + y def sub(x,y): return x - y def exam(): cmds = {'+':add,'-':sub} nums = [randint(1,100) for i in range(2)] #循环两次,每次从1-100选两个数 nums.sort(reverse=True) #sort(),排序,reverse=True,反转,最后列表是降序排列 op = choice('+-') result = cmds[op](*nums) #(*nums),将列表转换成元组,[op],['+']或['-'],cmds[op],字典cmds内[op]对应的值,即add或sub prompt = "%s %s %s = " % (nums[0],op,nums[1]) tries = 0 while tries < 3: try: #异常处理 answer = int(input(prompt)) except: #简单粗暴的捕获所有异常 continue if answer == result: print('Very good!') break else: print('Wrong answer') tries +=1 else: #while的else,全算错才给答案,答对了就不给出答案 print('%s%s' % (prompt,result)) if __name__ == '__main__': while True: exam() try: #异常处理 yn = input("Continue(y/n)?").strip()[0] #去除所有空格,取第一个字符 except ImportError: continue except (KeyboardInterrupt,EOFError): print() yn = 'n' if yn in 'Nn': break
#或
#转自https://www.jianshu.com/c/00c61372c46a网址 from random import randint,choice def exam(): cmds = {'+':lambda x,y:x + y,'-':lambda x,y:x - y} #lambda,匿名函数 nums = [randint(1,100) for i in range(2)] nums.sort(reverse=True) op = choice('+-') result = cmds[op](*nums) prompt = "%s %s %s = " % (nums[0],op,nums[1]) tries = 0 while tries < 3: try: answer = int(input(prompt)) except: continue if answer == result: print('Very good!') break else: print('Wrong answer.') tries +=1 else: print('%s%s' % (prompt,result)) if __name__ == '__main__': while True: exam() try: yn = input("Continue(y/n)?").strip()[0] except ImportError: continue except (KeyboardInterrupt,EOFError): print() yn = 'n' if yn in 'nN': break