---
title: "菜鸟学Python - 斐波那契数列(二)"
author: "ay_guobo"
date: "2011-10-30T07:33:54Z"
tags: []
categories: ["编程语言"]
slug: "python"
draft: false
lastmod: "2011-10-30T07:33:54Z"
id: 1222802
url: "https://GUOBO.iteye.com/blog/1222802"
---

上一次我们写了一个关于斐波那契数列的程序，为了提高对Python的灵活运用，这次再写一个小程序。

大家可以比较一下每个程序的优势，看看是否得到什么灵感。

01 import sys  
02   
03 # Here's our main function. Python is pretty efficient here. You  
04 # should notice that there are no braces. Python is dependant on  
05 # whitespace to define blocks.  
06   
07 def main():  
08   print "\\nHow many numbers of the sequence would you like?"  
09   n = int(sys.stdin.readline())  
10   fibonacci(n)  
11   
12 # Here's the fibonacci function. Like in Perl, you can assign multiple  
13 # variables on a line without using a temporary variable. Also, the for   
14 # loop here works more like a foreach loop by setting a range from 0 to n.  
15   
16 def fibonacci(n):  
17   a,b = 0,1  
18   for i in range(0,n):  
19     print a  
20     a,b, = b,a+b  
21   
22 main()

![菜鸟学Python - 斐波那契数列（Fibonacci）- 续（一） - 梦想社 - 梦想社](http://b.bst.126.net/common/portrait/frogleon/preview/frogleon5.gif)两个函数实现了这个算法：

1、main函数主要是获取用户输入，并执行程序。

2、fibonacci函数就是主要的算法实现了。

3、大家关键是看看程序的第20行，这个是程序的亮点。

如果是java呢？