python核心编程学习(四)

来源:互联网 发布:灵格斯 mac 编辑:程序博客网 时间:2024/06/11 15:25

一个计算简单加减法的例子:

'''Created on 2012-3-7@author: Administrator'''#!/usr/bin/env pythonfrom operator import add,subfrom random import randint,choiceops={'+':add,'-':sub}MAXTRIES=2def 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 =1correct!again?[y]y8 + 3 =11correct!again?[y]y8 - 6 =3incorrect... try again8 - 6 =2correct!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)。

原创粉丝点击