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

函数使用

定义函数:

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

#!/usr/bin/env python
def fibs(num):
	result = [0,1]
	for i in range(num-2):
		result.append(result[-2]+result[-1])
	return result
print 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 python
def foo():x=42
x=1
foo()
print x
1
#!/usr/bin/env python
def output(x):print x
x=1
y=2
output(y)
2
递归(阶乘与幂):

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

你可能感兴趣的:(python)