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 读文件,然后转化为矩阵的实例

代码流程: 1. 从文件中读入数据。 2. 将数据转化成矩阵的形式。 3. 对于矩阵进行处理。 具体的python代码如下: - 文件路径需要设置正确。 - 字符串处理。 - 字符串数...

pytorch中nn.Conv1d的用法详解

pytorch中nn.Conv1d的用法详解

先粘贴一段official guide:nn.conv1d官方 我一开始被in_channels、out_channels卡住了很久,结果发现就和conv2d是一毛一样的。话不多说,先...

python中lambda函数 list comprehension 和 zip函数使用指南

lambda 函数 Python 支持一种有趣的语法,它允许你快速定义单行的最小函数。这些叫做 lambda 的函数,是从 Lisp 借用来的,可以用在任何需要函数的地方。 def f...

Python中input与raw_input 之间的比较

Python中input与raw_input 之间的比较 input和raw_input均可以接收输入,其差别如下所示: #input假设用户输入的是合法的Python表达式 >...

python selenium 执行完毕关闭chromedriver进程示例

因为使用多次以后发现进程中出现了很多chromedriver的残留,造成卡顿,所以决定优化一下。 这个问题困扰了楼主很久,百度谷歌查来查去都只有java,后面根据java和seleniu...