python学习笔记(函数)

懒惰即美德

斐波那契数列

>>> fibs=[0,1]
>>> for i in range(8):
fibs.append(fibs[-2]+fibs[-1])

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

or

fibs=[0,1]
num=input('How many fibonacci numbers do you want?')
for i in range(num-2):
fibs.append(fibs[-2]+fibs[-1])
print fibs

 

创建函数

def hello(name):

   return 'hello'+name+'!'

>>> print hello('world')
helloworld!

def fibs(num):
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]
>>>

记录函数

给函数添加文档字符串

def square(x):
'Calculates the square of the number x.'
return x*x

---------------

>>> square.func_doc
'Calculates the square of the number x.'
>>>

>>> help(square)
Help on function square in module __main__:

square(x)
Calculates the square of the number x.

>>>

参数

>>> def try_to_change(n):
n='Mr.Gumby'


>>> name='Mrs.Entity'
>>> try_to_change(name)
>>> name
'Mrs.Entity'

>>> def change(n):
n[0]='Mr.Gumby'


>>> names=['Mrs.Entity','Mrs.Thing']
>>> change(names)
>>> names
['Mr.Gumby', 'Mrs.Thing']
>>>

关键字参数和默认值

>>> def hello_1(greeting,name):
print '%s ,%s' %(greeting,name)


>>> def hello_2(name,greeting):
print '%s,%s' %(name,greeting)


>>> hello_1('hello','world')
hello ,world
>>> hello_2('hello','world')
hello,world
>>> hello_1(greeting='hello',name='world')
hello ,world
>>> hello_2(greeting='hello',name='world')
world,hello
>>> def hello_3(greeting='hello',name='world'):
print '%s,%s' %(greeting,name)


>>> hello_3()
hello,world
>>> hello_3('Greetings')
Greetings,world
>>> hello_3('Greetings','universe')
Greetings,universe
>>> hello_3(name='Gumby')
hello,Gumby

>>> def hello_4(name,greeting='hello',punctuation='!'):
print '%s,%s%s'%(greeting,name,punctuation)


>>> hello_4('Mars')
hello,Mars!
>>> hello_4('Mars','Howdy')
Howdy,Mars!
>>> hello_4('Mars','Howdy','...')
Howdy,Mars...
>>> hello_4('Mars',punctuation='.')
hello,Mars.
>>> hello_4('Mars',greeting='Top of the morning to ya')
Top of the morning to ya,Mars!
>>> hello_4()#name也需要赋予默认值

Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
hello_4()
TypeError: hello_4() takes at least 1 argument (0 given)
>>>

 

 练习使用参数

>>> def story(**kwds):
return 'Once upon a time.there was a ' '%(job)s called %(name)s.'%kwds

>>> def power(x,y,*others):
if others:
print 'Recived redundant parameters:',others
return pow(x,y)

>>> def interval(start,stop=None,step=1):
'Imitates range() for step>0'
if stop is None:
start,stop=0,start
result=[]
i=start
while i<stop:
result.append(i)
i+=step
return result

>>> print story(job='king',name='Gumby')
Once upon a time.there was a king called Gumby.
>>> print story(name='Sir Robin',job='brave knight')
Once upon a time.there was a brave knight called Sir Robin.
>>> params={'job':'language','name':'Python'}
>>> print story(**params)
Once upon a time.there was a language called Python.
>>> del params['job']
>>> pirnt story(job='stroke of genius',**params)
SyntaxError: invalid syntax
>>> print story(job='stroke of genius',**params)
Once upon a time.there was a stroke of genius called Python.
>>> power(2,3)
8
>>> power(3,2)
9
>>> power(y=3,x=2)
8
>>> params=(5,)*2
>>> power(*params)
3125
>>> power(3,3,'hello,world')

Recived redundant parameters: ('hello,world',)
27
>>> interval(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> interval(1,5)
[1, 2, 3, 4]
>>> interval(3,12,4)
[3, 7, 11]
>>> power(*interval(3,7))
Recived redundant parameters: (5, 6)
81
>>>

作用域

>>> x=1
>>> scope=vars()
>>> scope['x']
1
>>> scope['x']+=1
>>> x
2
>>> def foo():
x=42


>>> x=1
>>> foo()
>>> x
1
>>> def output(x):
print x


>>> x=1
>>> y=2
>>> output(y)
2
>>> def combine(parameter):
print parameter+external


>>> external='berry'
>>> combine('Shrub')
Shrubberry
>>>

>>> x=1
>>> def change_global():
global x
x=x+1


>>> change_global()
>>> x
2
>>>

>>> def multiplier(factor):
def multiplyByFactor(number):
return number*factor
return multiplyByFactor

>>> double=multiplier(2)
>>> double(5)
10
>>> triple=multiplier(3)
>>> triple(3)
9
>>> multiplier(5)(4)
20
>>>

递归

>>> def factorial(n):
result=n
for i in range(1,n):
result*=i
return result

>>> n=10
>>> factorial(n)
3628800
>>>
>>> def factorial(n):
if n==1:
return 1
else:
return n* factorial(n-1)


>>> factorial(10)
3628800
>>> def power(x,n):
result=1
for i in range(n):
result *=x
result result

SyntaxError: invalid syntax
>>>
>>> def power(x,n):
result=1
for i in range(n):
result *=x
return result

>>> power(2,3)
8
>>> def power(x,n):
if n==0:
return 1
else:
return x*power(x,n-1)

 

def search(sequence,number,lower=0,upper=None):
if upper is None:upper =len(sequence)-1
if lower==upper:
assert number==sequence[upper]
return upper
else:
middle=(lower+upper)//2
if number>sequence[middle]:
return search(sequence,number,middle+1,upper)
else:
return search(sequence,number,lower,middle)

-----------------------------------

>>> seq=[34,67,8,123,4,100,95]
>>> seq.sort()
>>> seq
[4, 8, 34, 67, 95, 100, 123]
>>> search(seq,34)
2
>>> search(seq,100)
5

 

posted @ 2015-08-04 10:08  whats  阅读(348)  评论(0编辑  收藏  举报