Python快速学习第五天
2016-08-15       个评论
我要投稿

1、 函数

>>> import math

>>> y=math.sqrt

>>> callable(y)

True

>>> x=1

>>> callable(x)

False

>>>def fibs(num):

... 'Get fibonaqi sequnce! '

... result=[0,1]

... for i in range(num-2):

...result.append(result[-2]+result[-1])

... return result

...

>>>fibs(10)

[0, 1,1, 2, 3, 5, 8, 13, 21, 34]

help(fibs)

Help on function fibs in module __main__:

fibs(num)

Getfibonaqi sequnce!

...skipping...

Help on function fibs in module __main__:

fibs(num)

Getfibonaqi sequnce!

return后不加值，只表示函数的结束，而没有返回值，这样可以避免应该返回序列时，意外返回None

>>> def test():

... print 'tanggao'

... return

... print 'tanggao isgood'

...

>>> x=test()

tanggao

>>> print x

None

2、参数对外部变量影响

>>> def try_to_change(n):

... n=3

...

>>> t=4

>>> try_to_change(t)#虽然在函数内部重新赋值，但外部不变

>>> t

4

>>> def change(n):

...n[0]='tanggao'

...

>>> names=['hello','world']

>>> change(names)

>>> names

['tanggao', 'world']

>>> #采用普通方法进行模拟

...

>>> names=['hello','world']

>>> n=names

>>> n[0]='tanggao'

>>> names

['tanggao', 'world']

data = {

'first':{ 'Magus': 'Magus Lie Hetland'},

'middle':{'Lie': 'Magus Lie Hetland'},

'last':{'Hetland': 'Magus Lie Hetland'}

}

Python代码

1. >>>definit(data):#data作为存储表，初始化

2. data['first']={}

3. data['middle']={}

4. data['last']={}

5.

6. >>>defstore(data,full_name):#存储，将全名存储到表中

7. names=full_name.split()#将名字按空格(即first,middle,last)分开，返回列表，如'MaLiHe'返回['Ma','Li','He']

8. iflen(names)==2:names.insert(1,'')#若无中间名，则插入空来表示中间名['Mr','Zha']返回['Mr','','Zha']

9. labels='first','middle','last'#元组

10. forlabel,nameinzip(labels,names):#元组与序列间也可使用zip

11. people=lookup(data,label,name)

12. ifpeople:

13. people.append(full_name)

14. else:

15. data[label][name]=[full_name]#当键不存在时，自动添加键值对，

16. #但如果输出不存在键对应值，则报错

17.

18. >>>deflookup(data,label,name):#查找，根据label查找是name的中间人

19. returndata[label].get(name)

20.

21.

22. >>>MyNames={}

23. >>>init(MyNames)

24. >>>store(MyNames,'MagnusLieHetland')

25. >>>lookup(MyNames,'middle','Lie')

26. ['MagnusLieHetland']

27. >>>store(MyNames,'RobinHood')

28. >>>store(MyNames,'RobinLocksley')

29. >>>lookup(MyNames,'first','Robin')

30. ['RobinHood','RobinLocksley']

31. >>>store(MyNames,'Mr.Gumby')

32. >>>lookup(MyNames,'middle','')

33. ['RobinHood','RobinLocksley','Mr.Gumby']

Python代码

1. >>>definc(x):returnx+1

2.

3. >>>foo=10

4. >>>inc(foo)

5. 11

6. >>>foo#外部变量未发生变化

7. 10

8. >>>foo=inc(foo)#将foo重新赋值

9. >>>foo

10. 11

Python代码

1. >>>definc(x):x[0]=x[0]+1

2.

3. >>>foo=[10]

4. >>>inc(foo)

5. >>>foo

6. [11]

3. 关键字参数和默认值

Python代码

1. >>>defhello(name,greeting):

2. print'%s,%s!'%(greeting,name)

3.

4.

5. >>>hello('sun','Hello')#位置参数

6. Hello,sun!

7. >>>hello(name='Sun',greeting='Hello')#关键字参数

8. Hello,Sun!

9. >>>hello(greeting='Hello',name='Sun')#关键字参数，不必关心位置

10. Hello,Sun!

Python代码

1. >>>defhello(name='world',greeting='Hello'):

2. print'%s,%s!'%(greeting,name)

3.

4.

5. >>>hello()

6. Hello,world!

7. >>>hello('Sun')

8. Hello,Sun!

9. >>>hello(greeting='Hi')

10. Hi,world!

Python代码

1. >>>defhello(name,greeting='Hello',punc='!'):

2. print'%s,%s%s'%(greeting,name,punc)

3.

4.

5. >>>hello('Sun')

6. Hello,Sun!

7. >>>hello('Sun','Hi')

8. Hi,Sun!

9. >>>hello('Sun',punc='..')

10. Hello,Sun..

11. >>>hello()#因为name是必须要有，若有默认值，则可没有

12.

13. Traceback(mostrecentcalllast):

14. File"",line1,in

15. hello()

16. TypeError:hello()takesatleast1argument(0given)

17. >>>

4. 收集参数——在定义时使用*或**，用来收集参数，允许使用不定数量的参数

*：收集其余的位置参数并作为元组返回

Python代码

1. >>>defprint_params2(title,*params):

2. printtitle

3. printparams

4.

5.

6. >>>print_params2('Param:',1,2,3)

7. Param:

8. (1,2,3)#以元组形式返回

9. >>>print_params2('Param:')#不提供收集元素时，返回空元组

10. Param:

11. ()

12. >>>print_params2('Param:',1)

13. Param:

14. (1,)#只有一个元素时，仍为元组

**：收集其余的关键字参数并作为字典返回，可与其他混用

Python代码

1. >>>defprint_params3(x,y,z=3,*pospar,**keypar):

2. printx,y,z

3. printpospar

4. printkeypar

5.

6.

7. >>>print_params3(1,2,3,4,5,6,7,fool=1,bar=2)

8. 123

9. (4,5,6,7)

10. {'fool':1,'bar':2}

11. >>>print_params3(1,2)

12. 123

13. ()

14. {}

5. 收集参数的翻转过程——在调用时使用*或**，将参数分配到定义的参数中，用于字典或列表分割时

Python代码

2.

3. >>>params=(1,2)

5. 3

Python代码

1. >>>defhello(name,greeting):

2. print'%s,%s!'%(greeting,name)

3.

4.

5. >>>params={'name':'SirRobin','greeting':'Welcome'}

6. >>>hello(**params)

7. Welcome,SirRobin!

8.

9.

Python代码

1. #模拟步长大于0的range()

2. >>>interval(10)

3. start=0stop=10step=1

4. [0,1,2,3,4,5,6,7,8,9]

5. >>>definterval(start,stop=None,step=1):

6. 'Imitatesrange()forstep>0'

7. ifstopisNone:#若未给stop指定值

8. start,stop=0,start#多个赋值，0赋值给start，start的值赋值给stop

9. result=[]

10. i=start

11. whilei

12. result.append(i)

13. i+=step

14. returnresult

15.

16. #

17. >>>defstory(**kwds):

18. return'%(job)scalled%(name)s.'%kwds

19.

20. >>>defpower(x,y,*others):

21. ifothers:

23. returnpow(x,y)

24.

25. #使用

26. >>>params={'job':'language','name':'python'}

27. >>>printstory(**params)#调用时分割字典，定义中收集

28. languagecalledpython.

29. >>>delparams['job']

30. >>>printstory(job='test',**params)

31.

32. >>>power(2,3,'test')

34.

35. >>>params=(5,)*2#即(5,5)

36. >>>power(*params)#先分割，在赋给x，y

37. 3125

6.作用域

x = 1， 将名字x引用到值1上，类似字典

Python代码

1. >>>x=1

2. >>>scope=vars()

3. >>>scope['x']

4. 1

5. >>>scope['x']+=1#一般情况下，vars()返回的字典不能修改

6. >>>x

7. 2

Python代码

1. >>>defcom(para):printpara+external

2.

3. >>>external='external'

4. >>>com('param')

5. paramexternal

Python代码

1. >>>defcom(para):printpara+globals()['para']

2.

3. >>>para='berry'

4. >>>com('test')

5. testberry

Python代码

1. >>>x=1

2. >>>defchange_global():

3. globalx

4. x=x+1

5.

6.

7. >>>change_global()

8. >>>x

9. 2

Python代码

1. >>>defmultiplier(factor):

2. defmultiplyByFactor(number):

3. returnnumber*factor

4. returnmultiplyByFactor#返回一个函数，这时并未调用

5.

6. >>>double=multiplier(2)#double是一个函数

7. >>>double#double是一个函数

8.

9. >>>double(5)#调用multiplyByFactor(number)

10. 10

11. >>>multiplier(2)(5)#效果同上

12. 10

7. 递归——每调用一个函数，都会创建一个新的命名空间，意味着当函数调用自身时，实际上调用的是两个不同的函数

Python代码

1. >>>deffactorial(n):

2. ifn==1:

3. return1

4. else:

5. returnn*factorial(n-1)

6.

7. >>>factorial(5)

8. 120

Python代码

1. >>>defpower(x,n):

2. ifn==0:

3. return1

4. else:

5. returnx*power(x,n-1)

6.

7.

8. >>>power(2,3)

9. 8

Python代码

1. >>>defsearch(sequence,number,lower=0,upper=None):

2. ifupperisNone:upper=len(sequence)-1

3. iflower==upper:

4. assertnumber==sequence[upper]

5. returnupper

6. else:

7. middle=(lower+upper)//2

8. ifnumber>sequence[middle]:

9. returnsearch(sequence,number,middle+1,upper)

10. else:

11. returnsearch(sequence,number,lower,middle)

12.

13.

14. >>>seq=[34,67,8,123,4,100,95]

15. >>>seq.sort()

16. >>>seq

17. [4,8,34,67,95,100,123]

18. >>>search(seq,34)

19. 2

Python代码

1. >>>d={'a':1,'b':2}

2. >>>print'%(a)scorrespondsto%(b)s.'%d#注意a有括号，无引号

3. 1correspondsto2.