用户可以输入三次正确答案。三次不对则给出正确答案。
第一步:定义函数框架
def main():
while True:
arithmetic()
try:
goon = raw_input('next(y/n)').strip()[0]
except IndexError:
continue
except (EOFError,IOError):
goon = n
if goon in 'nN':
break
if __name__ =='__main__':
main()
第二步:定义四则运算函数 arithmetic( )
import random
import operator
ops={'+':operator.add,'-':operator.div}
def arithmetic():
nums =[random.randint(1,100) for i in range(2)]
nums.sort(reverse=True)
op = random.choice('+-')
print 'op',op
result = ops[op](*nums)
print 'result',result
prompt = '%s%s%s='%(nums[0],op,nums[1])
tries = 1
while tries <= 3:
try:
answer=int(raw_input(prompt))
except ValueError:
print 'input a number'
except (EOFError,IOError),e:
print 'Error',e
if answer == result:
print 'correct answer'
else:
print 'wrong answer'
tries +=1
else:
print 'correct answer :%s%s'%(prompt,result)
第三步:整理函数
#!/usr/bin/env python
#coding:utf8
import random
import operator
ops={'+':operator.add,'-':operator.div}
def arithmetic():
nums =[random.randint(1,100) for i in range(2)]
nums.sort(reverse=True)
op = random.choice('+-')
print 'op',op
result = ops[op](*nums)
print 'result',result
prompt = '%s%s%s='%(nums[0],op,nums[1])
tries = 1
while tries <= 3:
try:
answer=int(raw_input(prompt))
except ValueError:
print 'input a number'
except (EOFError,IOError),e:
print 'Error',e
if answer == result:
print 'correct answer'
else:
print 'wrong answer'
tries +=1
else:
print 'correct answer :%s%s'%(prompt,result)
def main():
while True:
arithmetic()
try:
goon = raw_input('next(y/n)').strip()[0]
except IndexError:
continue
except (EOFError,IOError):
goon = n
if goon in 'nN':
break
if __name__ =='__main__':
main()