1、创建函数: def关键字,将程序抽象,方便调用
例子:斐波那契数列
>>> 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]
2、文档字符串:给函数写注释和文档,方便后面使用函数的人理解
>>> def square(x):
... 'Calculates ther square of the number x.' 注释
... return x*x
>>> square.__doc__ 文档字符串
'Calculates ther square of the number x.'
__doc__是函数属性,双下划线表示它是一个特殊属性。
>>> help(square) 使用内建help函数查看
Help on function square in module __main__:
square(x)
Calculates ther square of the number x.
3、并非真正函数的函数:python有些函数并不返回任何东西,没有return或者有return但是不返回任何值。
>>> def test():
... print '1111'
... return 这里起到结束函数的作用,相当于循环中的break
... print '2222
>>> x = test()
1111
4、参数:形参,实参
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请
点击举报。