一个计算简单加减法的例子:
''' Created on 2012-3-7 @author: Administrator ''' #!/usr/bin/env python from operator import add,sub from random import randint,choice ops={'+':add,'-':sub} MAXTRIES=2 def doprob(): op=choice('+-') nums=[randint(1,10) for i in range(2)] nums.sort(reverse=True) ans=ops[op](*nums) pr='%d %s %d =' % (nums[0],op,nums[1]) oops = 0 while True: try: if int(raw_input(pr))==ans: print 'correct!' break if oops == MAXTRIES: 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()
运行喽:
3 - 2 =1 correct! again?[y]y 8 + 3 =11 correct! again?[y]y 8 - 6 =3 incorrect... try again 8 - 6 =2 correct! again?[y]
最值得注意的是:ans=ops[op](*nums) ,不知道什么意思,自己在IDLE上测试一下吧:
nu=[3,2]
from operator import add
add([3,2])
Traceback (most recent call last):
File "<pyshell#79>", line 1, in <module>
add([3,2])
TypeError: op_add expected 2 arguments, got 1
看来不行啊
但是add(*nu) 这样是可以的。
百思不解*nu是什么意思,.....经过朋友的帮助才知道是拆分传参,现在是把nu列表中的n个元素拆分,作为参数传给add()函数,还有一种传参是将字典类型的参数传入,然后拆分成多个参数,形式就是fun(**d)。