auden
auden

Reputation: 1157

Infinite loop in python - why?

I'm using the code

fibList=[1]

def fib(n1, n2):
    n3 = n1+n2
    n1=n2
    n2=n3

num1=1
num2=2

while(num2<4000000):
    fib(num1,num2)
        if (num2%2==0):
            fibList.append(num2)
total = sum(fibList)

print total

in an online compiler, repl.it. It was going and going and not giving a solution, so I typed the line print n3 right below the n3= line in the definition of the fib function. It gave 3, over and over again, and it crashed before I could stop the program. So obviously there's some kind of infinite loop somewhere (at least, obviously in my mind; it could not be an infinite loop, I suppose, but I'm pretty sure it is). The question is where. I don't really understand why there'd be an infinite loop.

This is not, by the way, a homework question, but a problem I'm doing for fun. The fib function is supposed to calculate Fibonacci numbers, and the second part isolate the even ones less than four million, and then at the end calculate the sum.

What I want to know is where the infinite loop is coming in and what I can do to fix it. Thanks!

Upvotes: 0

Views: 80

Answers (1)

Daniel
Daniel

Reputation: 42748

n1, n2 and n3 are local variables and have nothing in common with num1 and num2 in the outer scope, despite their initial value. You have to return the value and assign these results to num1 and num2 again.

def fib(n1, n2):
    n3 = n1+n2
    n1=n2
    n2=n3
    return n1, n2

num1=1
num2=2
fibList=[1]
while num2<4000000:
    num1, num2 = fib(num1,num2)
    if num2%2==0:
        fibList.append(num2)
total = sum(fibList)

print total

Upvotes: 6

Related Questions