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实现nao机器人身体躯干和腿部动作操作

本文实例为大家分享了python实现nao机器人身体躯干和腿部动作的具体代码,供大家参考,具体内容如下 跟上一篇类似,代码没什么难度,可以进行扩展。 #-*-encoding:UTF...

Python实现的tab文件操作类分享

类代码: # -*- coding:gbk -*- import os class TABFILE: def __init__(self, filename, dest_fi...

Python opencv实现人眼/人脸识别以及实时打码处理

Python opencv实现人眼/人脸识别以及实时打码处理

利用Python+opencv实现从摄像头捕获图像,识别其中的人眼/人脸,并打上马赛克。 系统环境:Windows 7 + Python 3.6.3 + opencv 3.4.2 一、系...

pygame库实现移动底座弹球小游戏

pygame库实现移动底座弹球小游戏

本文实例为大家分享了pygame实现移动底座弹球的具体代码,供大家参考,具体内容如下 输出结果:   实现代码: # -*- coding: utf-8 -*- #Py...

使用Python对Excel进行读写操作

学习Python的过程中,我们会遇到Excel的读写问题。这时,我们可以使用xlwt模块将数据写入Excel表格中,使用xlrd模块从Excel中读取数据。下面我们介绍如何实现使用Pyt...