• 欢迎访问开心洋葱网站,在线教程,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站,欢迎加入开心洋葱 QQ群
  • 为方便开心洋葱网用户,开心洋葱官网已经开启复制功能!
  • 欢迎访问开心洋葱网站,手机也能访问哦~欢迎加入开心洋葱多维思维学习平台 QQ群
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏开心洋葱吧~~~~~~~~~~~~~!
  • 由于近期流量激增,小站的ECS没能经的起亲们的访问,本站依然没有盈利,如果各位看如果觉着文字不错,还请看官给小站打个赏~~~~~~~~~~~~~!

用Python实现一个简单的算术游戏

python 水墨上仙 1193次浏览

用Python实现一个简单的算术游戏
来源:http://blog.csdn.net/buaa_shang/article/details/8315829

#!/usr/bin/env python
from operator import add, sub 
from random import randint, choice
ops = {'+': add, '-':sub}
#定义一个字典
MAXTRIES = 2 
def doprob():
    op = choice('+-')
    #用choice从'+-'中随意选择操作符 
    nums = [randint(1,10) for i in range(2)]
    #用randint(1,10)随机生成一个1到10的数,随机两次使用range(2) 
    nums.sort(reverse=True)
    #按升序排序
    ans = ops[op](*nums)
    #利用函数
    pr = '%d %s %d = ' % (nums[0], op, nums[1])
    oops = 0 
    #oops用来计算failure测试,当三次时自动给出答案
    while True:
        try:
            if int(raw_input(pr)) == ans:
                print 'correct'
                break
            if oops == MAXTRIES:
                print 'answer\n %s%d' % (pr, ans)
                break
            else:
                print 'incorrect... try again'
                oops += 1
        except (KeyboardInterrupt, EOFError, ValueError):
            print 'invalid ipnut... try again'
def main():
    while True:
        doprob()
        try:
            opt = raw_input('Again? [y]').lower()
            if opt and opt[0] == 'n':
                break
        except (KeyboardInterrupt, EOFError):
            break
if __name__ == '__main__':
    main()


开心洋葱 , 版权所有丨如未注明 , 均为原创丨未经授权请勿修改 , 转载请注明用Python实现一个简单的算术游戏
喜欢 (0)
加载中……