python 编程小实例(2) 四则运算小游戏




从1 到100之间随机选取俩个整数,使用大的数字加上或者除以小的数值。

用户可以输入三次正确答案。三次不对则给出正确答案。


第一步:定义函数框架

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()



智能推荐

注意!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系我们删除。



 
© 2014-2019 ITdaan.com 粤ICP备14056181号  

赞助商广告