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

相关文章

对python requests发送json格式数据的实例详解

requests是常用的请求库,不管是写爬虫脚本,还是测试接口返回数据等。都是很简单常用的工具。 这里就记录一下如何用requests发送json格式的数据,因为一般我们post参数,都...

Python Web框架Flask下网站开发入门实例

Python Web框架Flask下网站开发入门实例

一、Flask简介 Flask 是一个 Python 实现的 Web 开发微框架。官网:http://flask.pocoo.org/ 二、Demo 1、代码结构 复制代码 代码如下:...

Python Django 页面上展示固定的页码数实现代码

Python Django 页面上展示固定的页码数实现代码

如果页数太多的话,全部显示在页面上就会显得很冗杂 可以在页面中显示规定的页码数 例如: book_list.html: <!DOCTYPE html> <htm...

Python面向对象之类和实例用法分析

本文实例讲述了Python面向对象之类和实例用法。分享给大家供大家参考,具体如下: 类 虽然 Python 是解释性语言,但是它是面向对象的,能够进行对象编程。至于何为面向对象,在此就不...

python实现定时同步本机与北京时间的方法

本文实例讲述了python实现定时同步本机与北京时间的方法。分享给大家供大家参考。具体如下: 这段python代码首先从www.beijing-time.org上获取标准的北京时间,然后...