python列印斐波那契數列前n項或第n項

2021-09-10 06:51:56 字數 1446 閱讀 5141

nterms = int(input("你需要幾項?"))

# 第一和第二項

n1 = 0

n2 = 1

count = 2

# 判斷輸入的值是否合法

if nterms <= 0:

print("請輸入乙個正整數。")

elif nterms == 1:

print("斐波那契數列:")

print(n1)

else:

print("斐波那契數列:")

print(n1,",",n2,end=" , ")

while count < nterms:

nth = n1 + n2

print(nth,end=" , ")

# 更新值

n1 = n2

n2 = nth

count += 1

輸出結果:

你需要幾項?7

斐波那契數列:

0 , 1 , 1 , 2 , 3 , 5 , 8 ,

n=int(input('你需要幾項斐波那契數列值:'))

n1=1

n2=1

count=2

if n<=0:#判斷輸入值是否合法

print('輸入數字有誤')

elif n==1:

print(n1)

else:

print(n1,"",n2,end=" ")

while count輸出結果:

你需要幾項斐波那契數列值:5

1 1 2 3 5

def fabn(n):

n1=1

n2=1

count=2

if n<=0:

print('輸入數字有誤')

elif n==1:

print(1)

else:

print(n1,"",n2,end=" ")

while countdef fab(x):

n,a,b=0,0,1

while n輸出結果:

112

35813

2134

5589

144

n=int(input('你需要第幾項斐波那契數列值:'))

n1=1

n2=1

count=2

if n<=0:

print('輸入數字有誤')

elif n==1 or n==2:

print(1)

else:

while count輸出結果:

你需要第幾項斐波那契數列值:3

2

斐波那契數列 斐波那契數列python實現

斐波那契數列 fibonacci sequence 又稱 分割數列 因數學家列昂納多 斐波那契 leonardoda fibonacci 以兔子繁殖為例子而引入,故又稱為 兔子數列 指的是這樣乙個數列 1 1 2 3 5 8 13 21 34 在數學上,斐波納契數列以如下被以遞推的方法定義 f 1 ...

python 斐波那契數列

用python寫斐波那契數列當然大家都寫的出來。當時如果用一行 寫呢。本來沒有打算用一行 寫的。後來看到有用一行 寫階乘的。reduce lambda x,y x y,i for i in range 1,n 1 當然在這之前需要 from functools import 好吧,如果你願意,就算兩...

python斐波那契數列

學習過python基礎語法,我們嘗試做乙個簡單的斐波那契數列。斐波納契數列 兩個元素的總和確定了下乙個數 a,b 0,1 while b 10 print b a,b b,a b執行以上程式,輸出 112 358end關鍵字 關鍵字end可以用於將結果輸出到同一行,或者在輸出的末尾新增不同的字元,例...