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 = fib
f(50)
#方法即使没有return返回语句,也会返回值:None
print(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 n
def 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 result
print(fib2(100))
"""
result:
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
"""