您的位置:首页 > 编程语言 > Python开发

算术小游戏(python版)

2010-09-10 10:19 239 查看
来自《核心编程第二版》

#!/usr/bin/env python
#easyMath.py---it is a veryeasy children math game.
""" """
#use add(),sub(),and random number.
from operator import add,sub
from random import randint,choice
#operators are stored in the dict.
ops = {'+':add,'-':sub}
MAXTRIES = 2
def doprob():

#firstly,it must random choice an operator,
#and two number to reverse.
op = choice('+-')
nums = [randint(1,10) for i in range(2)]
nums.sort(reverse=True)

#get the value of ans.
ans = ops[op](*nums)
pr='%d %s %d='%(nums[0],op,nums[1])

#set the time of oops is 3,and if you input 3 times
#and the result is incorrect,it inputs the correct
#answer.
oops = 0
while True:
try:
if int(raw_input(pr)) == ans:  #the anwer is correct
print 'correct'
break

if oops == MAXTRIES:           #times=3 and incorrect
print 'answer/n%s%d'%(pr,ans)
else:
print 'incorrect... try again'
oops+=1
except (KeyboardInterrupt, /
EOFError,ValueError):
print 'invalid input... 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()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: