function在python_Python之function

1  Function

a function is a device that groups a set of statements so they can be run more than once in a program.

1)  def statements

def (arg1, arg2,... argN):

Function bodies often contain a return statement:

def (arg1, arg2,... argN):

...return

2)def executes at runtime

iftest:def func(): #Define func this way

...else:def func(): #Or else this way

...

...

func()#Call the version selected and buil

One way to understand this code is to realize that the def is much like an = statement: it simply assigns a name at runtime.

Unlike C, Python functions do not need to be fully defined before the program runs. More generally, defs are not evaluated until they are reached and run, and the code inside defs is not evaluated until the functions are later called.

Because function definition happens at runtime, there’s nothing special about function name. What’s important is the object to which it refers:

othername = func   #Assign function object

othername()   #Call func again

2  Example 1 - Definitions and Calls

1)  definition

>>> deftimes(x,y):

...return x *y

...

2)  call

>>> times(4,5)  # Arguments in parentheses20

>>> x = times(3.14,4)>>> x #Save the result object

12.56

>>> times('Ha',4)  # Functions are "typeless"'HaHaHaHa'

3  Example 2 - Intersecting Sequences

1)  definition

>>> defintersect(seq1,seq2):

... res=[]      # Start empty

...for x inseq1:      # Scan seq1

...if x inseq2:     # Common item?

... res.append(x)    # Add to end

...returnres

...

2)  call

>>> s1 = "SPAM"

>>> s2 = "SCAM"

>>> intersect(s1,s2) #Strings

['S', 'A', 'M']

>>> [x for x in s1 if x ins2]

['S', 'A', 'M']

3)  polymorphism revisited

>>> x = intersect([1,2,3],(1,4))  # Mixed types>>>x                  # Saved result object

[1]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值