0

Need to find the Fibonacci series up to N terms.

n=int(input("Enter the n terms: "))
f_val=0
fib_list=[f_val:=f_val + i for i in range(n)]
print(fib_list)

While executing the above program, I got the result:

Enter the n terms:  5
[0, 1, 3, 6, 10]

My doubt is: what is the purpose of f_val := f_val + i? I really don't know the purpose of := in Python. Can anyone help me to find the solution?

Jorge Luis
  • 813
  • 6
  • 21

1 Answers1

-2
n = int(input("Enter the number of terms: "))

f_val = 0
fib_list = [f_val := f_val + (fib_list[i-1] if i > 0 else 1) for i in range(n)]

print(fib_list)

Correct the code and solution of your doubt is: f_val is the variable that stores the current value of the Fibonacci-like series. f_val + i calculates the next term by adding the current value of f_val with the loop variable i. f_val := f_val + i assigns the new calculated value to f_val for the next iteration.

Jorge Luis
  • 813
  • 6
  • 21