随机从1到100随机取2个数值进行随机的相加减,输错3次给答案。
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)] # 随机取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("You are right!") break else: print("You are wrong!") tries += 1 else: # 猜对了直接跳出循环,3次全猜错了才执行,给出答案。 print("%s %s" %((prompt,result))) if __name__ == '__main__': while True: exam() try: yn = input("Continue(y/n)? ").strip()[0] print(yn) except IndexError: continue except (KeyboardInterrupt,EOFError): print() yn = 'n' if yn in 'nN': break
结果输出:
62 - 29 = 20 You are wrong! 62 - 29 = 30 You are wrong! 62 - 29 = 50 You are wrong! 62 - 29 = 33 Continue(y/n)? y y 25 + 16 = 41 You are right! Continue(y/n)? n n