zoukankan      html  css  js  c++  java
  • Python 函数练习数字游戏

    数学游戏

    编写一个简单的加减法数学游戏
    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
  • 相关阅读:
    WebAssembly学习(四):AssemblyScript
    Ramda
    React—生命周期
    网络拓扑图
    手机端的meta信息
    面试题
    Bootstrap路径导航
    Bootstrap 分页翻页
    Bootstrap栅格系统
    Bootstrap 屏幕类型
  • 原文地址:https://www.cnblogs.com/weiwenbo/p/6646340.html
Copyright © 2011-2022 走看看