博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
用Python实现一个简单的算术游戏
阅读量:2350 次
发布时间:2019-05-10

本文共 1116 字,大约阅读时间需要 3 分钟。

#!/usr/bin/env pythonfrom operator import add, sub from random import randint, choiceops = {'+': 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):            breakif __name__ == '__main__':    main()

转载地址:http://bihvb.baihongyu.com/

你可能感兴趣的文章
Column count doesn't match value count at row 1
查看>>
页面优化——js异步加载
查看>>
CSS3渐变
查看>>
CSS实现居中的7种方法
查看>>
Charles拦截不到请求
查看>>
gitlab/github 多账户下设置 ssh keys
查看>>
Mac版 charles安装与破解
查看>>
keydown、keypress、keyup的使用
查看>>
区块链是否做好了迎接法币的准备?为什么银行如此看好加密货币?
查看>>
加密货币--Cryptocurrency
查看>>
Myeclipse的不足之一,struts 配置 action
查看>>
input /button链接方法
查看>>
CSS,font-family,好看,常用,中文,字体(更新中)
查看>>
Redis---基础知识:数据类型、持久化机制、虚拟内存、高级特性、应用场景
查看>>
Python3---获取延迟、提前的时间、日期---datetime、time
查看>>
Python3+selenium+Chrome---获取表格(tbody)中数据(tr)的详细内容----a & td内容的获取
查看>>
Docker/Podman使用提高----Dockerfile的制作基础及常见的问题
查看>>
Jenkins持续部署---centos7+Docker+Github+Flask项目-------补丁篇
查看>>
C语言基础---指针数组----初始化方式&常量指针数组、指针常量数组
查看>>
C语言基础---数组、指针之间的相同与不同
查看>>