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

yipeiwu_com5年前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程序设计有所帮助。

相关文章

numpy.ndarray 交换多维数组(矩阵)的行/列方法

如下所示: >> import numpy as np >> P = np.eye(3) >> P array([[ 1., 0., 0.],...

Python3中函数参数传递方式实例详解

Python3中函数参数传递方式实例详解

本文实例讲述了Python3中函数参数传递方式。分享给大家供大家参考,具体如下: 之前在看北理工嵩天等老师的python3的课程,在第五周中老师讲到了函数的调用传递。老师讲了这样一个例子...

基于python中pygame模块的Linux下安装过程(详解)

一、使用pip安装Python包 大多数较新的Python版本都自带pip,因此首先可检查系统是否已经安装了pip。在Python3中,pip有时被称为pip3. 1、在Linux和OS...

pygame实现五子棋游戏

pygame实现五子棋游戏

本文实例为大家分享了pygame五子棋游戏的具体代码,供大家参考,具体内容如下 1.设置棋盘 五子棋标准棋盘是15x15的,如果我们每个格子的大小是40x40的话,棋盘应该是40x(15...

在Pandas中处理NaN值的方法

在Pandas中处理NaN值的方法

关于NaN值 -在能够使用大型数据集训练学习算法之前,我们通常需要先清理数据, 也就是说,我们需要通过某个方法检测并更正数据中的错误。 - 任何给定数据集可能会出现各种糟糕的数据,例如...