函数1-python

我们对函数是再熟悉不过了,Python中的函数是如何定义和实现的呢?看例子:

>>> defhello(name):

      return 'Hello %s' % name

 

>>> printhello('world')

Hello world

>>> printhello('Jimmy')

Hello Jimmy

>>> 

下面是实现Fibonacci序列的函数:

>>> deffibs(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]

>>> 

下面说几个小技巧:

1 当函数有多个参数时,我们在调用函数时,参数的位置是可以变得,只要我们指定哪个参数赋什么值即可,例如:

>>> defhello(greeting,name):

      print '%s,%s' % (greeting,name)

 

      

>>>hello('Hello','World')

Hello,World

>>>hello('World','Hello')

World,Hello

>>>hello(greeting='Hello',name='World')

Hello,World

>>>hello(name='World',greeting = 'Hello')

Hello,World

>>> 

这种方法不容易把参数弄混,特别是参数很多的情况下。

还有一点,函数如果有默认参数,则当你给他赋值时,则改变,不给他赋值,则保持原来的值。这就相当灵活了,比如看下面的例子:

>>> defhello(name,greeting='Hello',punctuation='!'):

      print '%s,%s%s' % (greeting,name,punctuation)

>>>hello('Mars')

Hello,Mars!

>>>hello('Mars','Hi')

Hi,Mars!

>>>hello('Mars','Hi','....')

Hi,Mars....

>>>hello('Mars',punctuation='.')

Hello,Mars.

>>>hello('Mars',greeting='Top of the morning to ya')

Top of the morning to ya,Mars!

>>> hello()

 

Traceback (most recent call last):

  File"<pyshell#71>", line 1, in<module>

   hello()

TypeError: hello() takes at least 1 argument (0 given)

>>> 

So that is pretty flexible,isn’t it?

 

2 星号的作用:

 参数前一个星号,看例子:

>>> defprint_params(*params):

      print params

 

      

>>>print_params('Testing')

('Testing',)

>>>print_params(1,2,3)

(1, 2, 3)

>>>print_params(1,2,[1,2],'dd')

(1, 2, [1, 2], 'dd')

可以看到自动把后面的参加一起形成了一个元组。

参数前两个星号:

>>> defprint_params1(**params):

      print params

>>>print_params1(x=1,y=2,z=3)

{'y': 2, 'x': 1, 'z': 3}

可以看到我们得到了一个字典。


 还有一点需要说明,就是我们在使用系统提供的函数的时候,我们只知道函数的名字,但是我们想知道函数大概是干嘛的,这时候我们可以用help命令来取得函数的帮助信息,比如:

>>> help(open)

Help on built-in function open in module __builtin__:

 

open(...)

   open(name[, mode[, buffering]]) -> file object

   

    Open afile using the file() type, returns a fileobject.  This is the

    preferredway to open a file.

 

>>> 

可以看到关于open函数的一些情况。如果我们自己编了一些函数,而可能别人要使用我们写的函数,那么为了方便别人使用,也能用help命令得到我们所写的函数的帮助信息该如何实现呢,其实很简单,看下面的例子:

>>> defsquare(x):

      'calculate the square of the nubmer x.'

      return x*x

 

>>> square(3)

9

>>>help(square)

Help on function square in module __main__:

 

square(x)

calculate the square of the nubmer x.

可以看到我们在函数中用字符串引起的信息在help的命令下显示了,这样就能方便其他的用户使用了。


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值