首页 > 编程语言 > 详细

Python 函数练习数字游戏

时间:2017-03-30 15:26:52      阅读:266      评论:0      收藏:0      [点我收藏+]

数学游戏

编写一个简单的加减法数学游戏
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 "\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 函数练习数字游戏

原文:http://www.cnblogs.com/weiwenbo/p/6646340.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!