Python之函数

来源:互联网 发布:arm十linux 编辑:程序博客网 时间:2024/06/06 18:31
def fib(n): #write Fibonacci series up to n    #在Java和C语言中不能赋予两个不同的变量不同的值,但是在Python中是可以的    a,b = 0, 1    while a < n:        print(a, end=', ')        a, b = b, a+b    print()#Now call the function we just defined:fib(100)f = fibf(50)#方法即使没有return返回语句,也会返回值:Noneprint(fib(0))"""result:0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 0, 1, 1, 2, 3, 5, 8, 13, 21, 34,None方法的定义:def 方法名(参数列表):    方法体注:方法体必须是在下一行,而且必须缩进"""

# return Fibonacci series up to ndef fib2(n):    #Return a list containing the Fibonacci series up to n.     result = []     a, b = 0, 1     while a < n:         result.append(a)    # see below         #下面的表达形式和上面的效果是相同的         #result = result + [a]         a, b = b, a+b    #return 如果没有表达式参数将会返回None     return resultprint(fib2(100))"""result:[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]"""