python核心编程学习(四)
一个计算简单加减法的例子:'''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=nums.sort(reverse=True)ans=ops(*nums)pr='%d %s %d =' % (nums,op,nums)oops = 0while True:try:if int(raw_input(pr))==ans:print 'correct!'breakif oops == MAXTRIES:print 'answer \n%s%d' %(pr,ans)else:print 'incorrect... try again'oops+=1except(KeyboardInterrupt,EOFError,ValueError):print 'invalid input... try again'def main():while True:doprob()try:opt = raw_input('again?').lower()if opt and opt=='n':breakexcept(KeyboardInterrupt,EOFError):breakif __name__=='__main__':main()
运行喽:
3 - 2 =1correct!again?y8 + 3 =11correct!again?y8 - 6 =3incorrect... try again8 - 6 =2correct!again?
最值得注意的是:ans=ops(*nums) ,不知道什么意思,自己在IDLE上测试一下吧:
nu=
from operator import add
add()
Traceback (most recent call last):
File "<pyshell#79>", line 1, in <module>
add()
TypeError: op_add expected 2 arguments, got 1
看来不行啊
但是add(*nu) 这样是可以的。
百思不解*nu是什么意思,.....经过朋友的帮助才知道是拆分传参,现在是把nu列表中的n个元素拆分,作为参数传给add()函数,还有一种传参是将字典类型的参数传入,然后拆分成多个参数,形式就是fun(**d)。
页:
[1]