Beginning Python From Novice to Professional (6) - 函数使用

来源:互联网 发布:数据分析模型作用 编辑:程序博客网 时间:2024/03/29 21:31

函数使用

定义函数:

#!/usr/bin/env pythondef hello(name):return 'Hello, ' + name + ''print hello('world')print hello('Gumby')
Hello, worldHello, Gumby
斐波那契序列举例:

#!/usr/bin/env pythondef fibs(num):result = [0,1]for i in range(num-2):result.append(result[-2]+result[-1])return resultprint fibs(10)print fibs(15)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34][0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, 233, 377]
全局变量、局部变量:

#!/usr/bin/env pythondef foo():x=42x=1foo()print x
1
#!/usr/bin/env pythondef output(x):print xx=1y=2output(y)
2
递归(阶乘与幂):

#!/usr/bin/env pythondef factorial(n):if n==1:return 1else:return n * factorial(n-1)print factorial(4)
24
#!/usr/bin/env pythondef power(x,n):if n==0:return 1else:return x * power(x,n-1)print power(2,3)
8

1 0
原创粉丝点击