Fibonacci Sequence
The Fibonacci sequence, also known as the golden ratio sequence, is defined as follows: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, ….
Mathematically, the Fibonacci sequence is defined recursively:
F0 = 0 (n=0)
F1 = 1 (n=1)
Fn = F[n-1]+ F[n-2](n=>2)
1. Implementing the Fibonacci Sequence in Python
1. Using a simple method:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def fib(n):
a, b = 1, 1
for i in range(n - 1):
a, b = b, a + b
return a
# Output the 10th Fibonacci number
print(fib(10))
2. Using recursion:
#!/usr/bin/python
# -*- coding: UTF-8 -*-
# Using recursion
def fib(n):
if n == 1 or n == 2:
return 1
return fib(n - 1) + fib(n - 2)
# Output the 10th Fibonacci number
print(fib(10))
The above example outputs the 10th Fibonacci number, which is:
55
2. Outputting a specified number of Fibonacci numbers
#!/usr/bin/python
# -*- coding: UTF-8 -*-
def fib(n):
if n == 1:
return [1]
if n == 2:
return [1, 1]
fibs = [1, 1]
for i in range(2, n):
fibs.append(fibs[-1] + fibs[-2])
return fibs
# Output the first 10 Fibonacci numbers
print(fib(10))
The above program outputs the result:
[1, 1, 2, 3, 5, 8, 13, 21, 34, 55]
Else Statement
The else statement follows the if statement and contains code that is executed when the if statement evaluates to false.
Like the if statement, the code block should be indented.
x=4
if x==5:
print(“Yes”)
else:
print(“NO”)
Result:
>>>
NO
Nested Else
You can determine which option is correct among a series of possibilities using chained if statements and other statements. For example:
num=7
if num==5:
print(“number is 5”)
elif num==11:
print(“numbei is 11”)
elif num==7:
print(“number is 7”)
else:
print(“number isn’t 5, 11 or 7”)
Result:
>>>
number is 7
if(1==1)and(2+2>3):
print(“True”)
else:
print(“false”)
Result:
>>>
True
Follow our public account to receive red envelopes daily