0

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!

6
  • please fix the indentation in your code snippet Commented Aug 17, 2016 at 21:12
  • 1
    where are you changing the value of num2 in your loop? Commented Aug 17, 2016 at 21:13
  • 3
    calling fib does not change values of n1 and n2 outside of function body. Commented Aug 17, 2016 at 21:13
  • 3
    Possible duplicate of How do I pass a variable by reference? Commented Aug 17, 2016 at 21:13
  • 1
    The fib function just assigns values to the local n1, n2, n3 variables. This has no effect outside of the function. Commented Aug 17, 2016 at 21:14

1 Answer 1

6

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
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you; this helped a lot. Sorry I didn't accept sooner!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.