Python实现的简单算术游戏实例

yipeiwu_com6年前Python基础

本文实例讲述了Python实现的简单算术游戏。分享给大家供大家参考。具体实现方法如下:

#!/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()

运行结果如下:

8 - 1 = 7
correct
Again? [y]y
7 - 1 = 6
correct
Again? [y]y
9 + 4 = 0
incorrect... try again
9 + 4 = 

希望本文所述对大家的Python程序设计有所帮助。

相关文章

Django的信号机制详解

Django提供一种信号机制。其实就是观察者模式,又叫发布-订阅(Publish/Subscribe) 。当发生一些动作的时候,发出信号,然后监听了这个信号的函数就会执行。 Django...

Flask框架学习笔记(一)安装篇(windows安装与centos安装)

Flask 依赖于两个外部库: Werkzeug  和  Jinja2  。 Werkzeug 是一个 WSGI (在 web 应用和多种服务器之间开发和部...

详解Python装饰器

1. 定义 本质是函数,用来装饰其他函数,为其他函数添加附加功能 2. 原则 a. 不能修改被装饰函数的源代码 b. 不能修改被装饰的函数的调用方式 3. 实现装饰器知识储备 a. 函数...

python使用rsa加密算法模块模拟新浪微博登录

PC登录新浪微博时,在客户端用js预先对用户名、密码都进行了加密,而且在POST之前会GET一组参数,这也将作为POST_DATA的一部分。这样,就不能用通常的那种简单方法来模拟POST...

python的Tqdm模块的使用

Tqdm 是一个快速,可扩展的Python进度条,可以在 Python 长循环中添加一个进度提示信息,用户只需要封装任意的迭代器 tqdm(iterator)。 我的系统是window...