数学游戏
编写一个简单的加减法数学游戏
1.随机生成两个100以内的数字
2.随机选择加法或是减法
3.总是使用大的数字减去小的数字
4.如果用户答错三次,程序给出正确答案
#!/usr/bin/env python import random import sys def add(x,y): return x + y def sub(x,y): return x - y def probe(): CMDs = {'+':add,'-':sub} alist = [random.randint(1,50) for i in range(2)] alist.sort(reverse=True) op = random.choice(CMDs.keys()) answer = CMDs[op](*alist) prompt = """%s %s %s:""" %(alist[0],op,alist[1]) i = 0 while i < 3: try: result = int(raw_input(prompt)) except (KeyboardInterrupt,EOFError),e: print " User cancelled" sys.exit() except (ValueError,IndexError,UnboundLocalError): print "Invaild" if answer == result: print "very good" break print "input wrong still %d chance" % (2-i) i += 1 else: print ("%s%s") % (prompt,answer) if __name__ == '__main__': while True: probe() yn = raw_input("continue(y/n)?>:".strip()[0]) if yn in 'Nn': print "bye-bye" break