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

相关文章

Python简单读写Xls格式文档的方法示例

Python简单读写Xls格式文档的方法示例

本文实例讲述了Python简单读写Xls格式文档的方法。分享给大家供大家参考,具体如下: 1. 模块安装 使用pip install命令安装, 即: pip install xlrd...

举例讲解Python中的身份运算符的使用方法

举例讲解Python中的身份运算符的使用方法

Python身份运算符 身份运算符用于比较两个对象的存储单元 以下实例演示了Python所有身份运算符的操作: #!/usr/bin/python a = 20 b = 20...

深入了解Python枚举类型的相关知识

枚举类型可以看作是一种标签或是一系列常量的集合,通常用于表示某些特定的有限集合,例如星期、月份、状态等。 Python 的原生类型(Built-in types)里并没有专门的枚举类型,...

Python中.py文件打包成exe可执行文件详解

Python中.py文件打包成exe可执行文件详解

前言 最近做了几个简单的爬虫python程序,于是就想做个窗口看看效果。 首先是,窗口的话,以前没怎么接触过,就先考虑用Qt制作简单的ui。这里用前面sinanews的爬虫脚本为例,制作...

在Django中创建动态视图的教程

在我们的`` current_datetime`` 视图范例中,尽管内容是动态的,但是URL ( /time/ )是静态的。 在 大多数动态web应用程序,URL通常都包含有相关的参数。...