首页 > 代码库 > Python 函数练习数字游戏

Python 函数练习数字游戏

数学游戏

编写一个简单的加减法数学游戏
1.随机生成两个100以内的数字
2.随机选择加法或是减法
3.总是使用大的数字减去小的数字
4.如果用户答错三次,程序给出正确答案
#!/usr/bin/env pythonimport randomimport sysdef add(x,y):   return x + ydef sub(x,y):    return  x - ydef 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 "\nUser 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

 

Python 函数练习数字游戏