For Loop Fibonacci Sequence - I don't understand the loop

Machine-specific discussion
Unix, Linux, OS X, OS/2, Windows, ..?
Locked
Mobo01
Posts: 8
Joined: Thu Jun 23, 2022 8:57 am

For Loop Fibonacci Sequence - I don't understand the loop

Post by Mobo01 »

I'm new to Python and attempting to figure out how I'm obtaining the right response.
Create code that:
  • The first 50 terms of the Fibonacci sequence are calculated and printed.
  • Each phrase and number should be printed as follows:

Code: Select all

term: 0 / number: 0
term: 1 / number: 1
term: 2 / number: 1
term: 3 / number: 2
term: 4 / number: 3
term: 5 / number: 5
I got the correct answer, but what about the "else" part?

Code: Select all

c = a + b
print(f'term: {term} / number: {c}')
a = b
b = c
Could someone perhaps explain how the variable above changes each time it loops? I'm not sure how c = 1 + 1 produces c = 2, but how does it then print c = 3?

Code: Select all

a = 1
b = 1
for term in range (50):
    if term <= 1:
        print(f'term: {term} / number: {term}')
    elif term == 2:
        print(f'term: {term} / number: 1')
    else:
        c = a + b
        print(f'term: {term} / number: {c}')
        a = b
        b = c
I saw an article that urged utilizing iterative rather than recursive methods. Will it be successful? Could you pls help me?

Locked