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

时间: 2024-08-28 16:45:55

python学习笔记(函数)的相关文章

python 学习笔记 函数和类

与java类似 python的函数也是出于可以复用才使用的 如果一段代码没有复用的价值就可以不用函数 一般的函数可以定义成这样: def func(a,b=123,*arg,**args): for x in arg:#arg是一个list print x for x,y in args.items():#args是一个dict print x,y print 'a:',a print 'b:',b func(1,1,2,3,4,c=1,d=2) 结果: 2 3 4 c 1 d 2 a: 1 b

python学习笔记 - 函数,集合,包,模块

一.函数 a=1, b=2, 交换值 定义中间量c,C=None, a,b=b,a a,b,c=1,2,3 sys.argv 实现指定的某些功能,使用的时候可以直接调用,简化代码,提高代码复用性 def fun():#定义一个函数,后面是函数名                print("Hello World")#函数体 例如: 1.def sayHello(): print("Hello World") sayHello()  --调用 2.def sayNam

Python学习笔记——函数

1.定义函数: 在Python中,定义一个函数要使用def语句,依次写出函数名.括号.括号中的参数和冒号:,然后,在缩进块中编写函数体,函数的返回值用return语句返回.如果一个函数什么也不做,需要用到pass语句(C,Java中可以直接不写代码,python必须要写pass占位,否则报错). def my_abs(x): if x >= 0: return x else: return -x 2.参数检查: isinstance(object, classinfo),其第一个参数为对象,第二

Python学习笔记-函数篇

定义 返回单值 def my_abs(x): if x >= 0: return x else: return -x 返回多值 返回多值就是返回一个tuple import math def move(x, y, step, angle=0): nx = x + step * math.cos(angle) ny = y - step * math.sin(angle) return nx, ny 空函数 def nop(): pass 指定默认参数 必选参数在前,默认参数在后.默认参数需指向不

Python 学习笔记-函数(一)传参

首先明确字符串,数字和元组作为函数参数时是不可变的,但是列表和字典等数据结构却是可以改变的. def change(n):     n[0]='apple' names=['banana','pear'] n=names[:] change(n) print names,n ['banana', 'pear'] ['apple', 'pear'] 修改后让原始列表保持不变. 假设现在要编写一个存储姓名, 年龄,部门并能够根据这三样进行联系人查询的程序: 因为是查询多个元素,首先想到了字典这种数据

Python学习笔记#函数中使用文档,让你的函数更容易理解

>>> def intadd(a,b): 'this is a test of the doc of function' return a+b >>> intadd(2,3) 5 >>> intadd.__doc__ 'this is a test of the doc of function' >>>

python学习笔记11-python内置函数

python学习笔记11-python内置函数 一.查看python的函数介绍: https://docs.python.org/2/library/ 二.python内置函数 1.abs获取绝对值: 通过python官网查看abs abs(x) Return the absolute value of a number. The argument may be a plain or long integer or a floating point number. If the argument

python学习笔记之函数总结--高阶函数以及装饰器

python学习笔记之函数总结--高阶函数以及装饰器 Python特点: 1.不是纯函数式编程(允许变量存在): 2.支持高阶函数(可以传入函数作为变量): 3.支持闭包(可以返回函数): 4.有限度的支持匿名函数: 高阶函数: 1.变量可以指向函数: 2.函数的参数可以接收变量: 3.一个函数可以接收另一个函数作为参数: 下面我将示例一些函数的写法以及使用,并说明python中函数的特性: 1.基本的高阶函数示例: #!/usr/bin/env python def func():      

python学习笔记(03):函数

默认参数值:   只有在行参表末尾的哪些参数可以有默认参数值,即 def func(a, b=5 )#有效的 def func( a=5,b )#无效的 关键参数: #!/usr/bin/python # Filename: func_key.py def func(a, b=5, c=10): print 'a is', a, 'and b is', b, 'and c is', c func(3, 7) func(25, c=24) func(c=50, a=100) #输出: $ pyth

Python学习笔记010——匿名函数lambda

1 语法 my_lambda = lambda arg1, arg2 : arg1 + arg2 + 1 arg1.arg2:参数 arg1 + arg2 + 1 :表达式 2 描述 匿名函数不需要return来返回值,表达式本身结果就是返回值. lambda 仅简洁了代码,并不会提高程序运行效率 如果可以用 for...in...if 来完成的,最好不使用匿名函数lambda 使用lambda时,函数内不要包含循环.嵌套:如果存在,则最好使用def函数来完成,这样的代码可读性和复用性均较高 l