ϕ0=0, ϕ1=1, ϕn=ϕn−1+ϕn−2.
|
n = int(input()) if n == 0: print(0) elif n == 1: print(1) else: fib_0 = 0 fib_1 = 1 for _ in range(2, n + 1): fib_n = fib_0 + fib_1 fib_0 = fib_1 fib_1 = fib_n print(fib_n) |
Explanation of the Code
- Reading Input:
- The
input()
function reads a line of text from the user.
- The
int()
function converts this input to an integer and stores it in the variable n
.
- Handling Base Cases:
if n == 0:
print(0)
elif n == 1:
print(1)
- If nnn is 0, print 0.
- If nnn is 1, print 1.
- Calculating Fibonacci Number Using a For Loop:
else:
fib_0 = 0
fib_1 = 1
for _ in range(2, n + 1):
fib_n = fib_0 + fib_1
fib_0 = fib_1
fib_1 = fib_n
print(fib_n)
- Initialize
fib_0
to 0 and fib_1
to 1.
- Use a
for
loop to iterate from 2 to nnn.
- In each iteration, calculate the next Fibonacci number (
fib_n
) as the sum of the previous two Fibonacci numbers.
- Update
fib_0
to the value of fib_1
and fib_1
to the value of fib_n
.
- After the loop, print the value of
fib_n
.