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编程中time模块的使用

一、简介 time模块提供各种操作时间的函数 说明:一般有两种表示时间的方式: 第一种是时间戳的方式(相对于1970.1.1 00:00:00以秒计算的偏移量),时间戳是惟一的 第二种以...

numpy 计算两个数组重复程度的方法

最近有个需求,是做两个数组重复程度计算,麻烦就麻烦在单个数组的元素有可能重复,处理思路如下: 1. 找到重复元素 2. 元素个数统计,利用np.bincount转换,即元素个数统计到元素...

python利用hook技术破解https的实例代码

相对于http协议,http是的特点就是他的安全性,http协议的通信内容用普通的嗅探器可以捕捉到,但是https协议的内容嗅探到的是加密后的内容,对我们的利用价值不是很高,所以一些大的...

Python实现在tkinter中使用matplotlib绘制图形的方法示例

Python实现在tkinter中使用matplotlib绘制图形的方法示例

本文实例讲述了Python实现在tkinter中使用matplotlib绘制图形的方法。分享给大家供大家参考,具体如下: 一. 代码: # coding=utf-8 import s...

Django项目中使用JWT的实现代码

Django项目中使用JWT的实现代码

1.requiremwnts: Django版本:2.2 python版本:3.6 djangorestframework版本:3.1 djangorestframew...