2013-08-02 186 views
2

我想了解Python,但我仍然不明白。我對這門語言很陌生,並且想要正確理解它。 這是一個使用循環的斐波那契數列。請解釋此代碼的含義。我正在嘗試手動獲取模式。我得到了3模式,但3後我沒有得到答案。斐波那契序列python

a, b = 0, 1 
while b < 50: 
    print(b) 
    a, b = b, a + b 
+0

有在那裏沒有迭代器。 –

回答

8
a, b = b, a + b 

這就是所謂的多重任務。這基本上是一個原子版本:

a = b 
b = a + b 

原子,我的意思是右邊一切之前計算它踱步到左邊的變量。所以a成爲bb成爲版本的ab,相當於非原子:

old_a = a 
a = b 
b = old_a + b 

因此,在以下方面你所看到的:

 a      b    output 
================ ========================= ====== 
(initial values)  (initial values) 
     0      1     1 
(becomes prev b) (becomes sum of prev a,b) 
     1      1     1 
     1      2     2 
     2      3     3 
     3      5     5 
     5      8     8 

,準確的代碼(以及多重任務的解釋)可以在教程中找到here

3

這是多重assigment(或元組拆包)。

根據Python Tutorial

>>> # Fibonacci series: 
... # the sum of two elements defines the next 
... a, b = 0, 1 
>>> while b < 10: 
...  print(b) 
...  a, b = b, a+b 
... 
1 
1 
2 
3 
5 
8 

這個例子引入了一些新的特點。

第一行包含多個參數:變量a和b 同時獲得新的值0和1.這是 再次使用的最後一行,這表明在右側 表達式都在任何任務發生之前首先進行評估。 右側表達式從左到右評估。

1

多重答案如何?

def fib(num): 
    a = 0 
    b = 1 
    while b <= num: 
     prev_a = a 
     a = b 
     b = prev_a +b 
     #print b                           
    return a 

print fib(13) 

def pythonic_fib(num): 
    a,b = 0,1 
    while b <= num: 
     a,b = b, a+b 
    return a 

print pythonic_fib(13) 

def recursive_fib(num, a, b): 
    if (b >= num): 
     return b 
    else: 
     return recursive_fib(num, b, a+b) 

print recursive_fib(13, 0, 1) 
0
#The easy way to generate Fibonacci series in python is 
user = input('Please enter the integer range for Fibonacci series: '); # take input from user form the range of Fibonacci series. 
try:# to ignore wrong inputs and be aware from error we use try and except block 
    d=int(user);# converts the user input to type integer. 
    a=0; #initialization`` 
    b=1; #initialization 
    print(a,b,end=' '); # print initial value of a and b 
    for c in range(0,d): # here c is iterable variable and in range o is the starting point and d is the ending range which we get from user 
     c=a+b; 
     a=b; 
     b=c; 
     print(c,end=' '); 

except Exception as e: 
    print(e); # if any error occurred in the input here it shows which error occurs 
0
a= int(input("Enter the first number:")); 
Enter the first number:0 
b= int(input("enter the second number:")); 
enter the second number:1 
n= int (input("enter the number of terms:")); 
enter the number of terms:10 
print(a,b); 
0 1 
while(n>2): 
     c=a+b; 
     a=b; 
     b=c; 
     print(c); 
     n=n-1; 


1 
2 
3 
5 
8 
13 
21 
34 
+0

這將是很好的提供你的代碼的一些解釋。 –