Python学習(五)——定義関数

492 ワード

学習は、戻り値と戻り値のない関数を定義します.
#! coding:utf-8
#             
def fib1(n):
	"""print a Fibnoacci series up to n."""
	a,b=0,1
	while a<n:
		print(a,end=' ')
		a,b=b,a+b
	print()

#            
def fib2(n):
	"""return a list of a Fibnoacci series up to n."""
	result=[]
	a,b=0,1
	while a<n:
		result.append(a)
		a,b=b,a+b
	return result

#     
result=fib2(20)
print(result)

実行結果:
[0, 1, 1, 2, 3, 5, 8, 13]