Python Fibonacci Sequence
The Fibonacci sequence is a sequence like this: 0, 1, 1, 2, 3, 5, 8, 13. In particular, the 0th term is 0, and the 1st term is the first 1. Starting from the third term, each term is equal to the sum of the previous two terms.
The code for implementing the Fibonacci sequence in Python is as follows:
Example (Python 3.0+)
# -*- coding: UTF-8 -*-
# Filename : test.py
# author by : www.example.com
# Python Fibonacci sequence implementation
# Get user input data
nterms = int(input("How many terms do you need?"))
# First and second terms
n1 = 0
n2 = 1
count = 2
# Check whether the input value is valid
if nterms <= 0:
print("Please enter a positive integer.")
elif nterms == 1:
print("Fibonacci sequence:")
print(n1)
else:
print("Fibonacci sequence:")
print(n1,",",n2,end=" , ")
while count < nterms:
nth = n1 + n2
print(nth,end=" , ")
# Update values
n1 = n2
n2 = nth
count += 1
The output of executing the above code is:
你需要几项? 10 斐波那契数列: 0 , 1 , 1 , 2 , 3 , 5 , 8 , 13 , 21 , 34 ,Other Extensions
Python3 Examples