一聚教程网:一个值得你收藏的教程网站

最新下载

热门教程

python函数定义与实例

时间:2011-05-08 编辑:简简单单 来源:一聚教程网

python函数定义下面几个实例是从最简单函数返回值到最函数里面更复杂的表达式,但不管怎么变是离不开函数这个东东。

def square(x):
    'Calculates the square of the number x.'
    return x*x


print square(100)

实例二

def power(x, n):
    if n == 0:
        return 1
    else:
        return x * power(x, n-1)


print power(2,7)

函数实例三

def hello():
    print "Hello, world!"

def test():
    hello()

if __name__ == '__main__': test()


实例四

def fib(n):    # write Fibonacci series up to n
     """Print a Fibonacci series up to n."""
     a, b = 0, 1
     while b < n:
         print b,
         a, b = b, a+b
 
# Now call the function we just defined:
fib(2000)

系统函数调用

def fib(n):    # write Fibonacci series up to n
     """Print a Fibonacci series up to n."""
     a, b = 0, 1
     while b < n:
         print b,
         a, b = b, a+b
 
# Now call the function we just defined:
fib(2000)

热门栏目