While loop code keeps running

For some reason this code doesn't print anything and doesn't stop running, can anybody tell me what is going wrong here?

l = [1,2]
i = 0
k = l[i]+l[i+1]
while k <= 10:
    l.append(k)
    i += 1

print l

Answers


The value of k (and therefore the loop condition) is set before the loop using the current value of i (0), and never changes during the loop execution. You would have to reassign k based on the new value for i inside the loop for it to change.


Python evaluates the value of k so that k isn't the expression, but the result of that expression:

k = l[i]+l[i+1]   # In your case it's l[0] + l[1] = 3

You probably want to evaluate k every loop:

l = [1,2]
i = 0

for i in range(0, 10 + 1):
  l.append(l[i] + l[i + 1])

print l

And just for fun, a more Pythonic Fibonacci sequence generator (literally):

def Fibonacci():
  a, b = 0, 1

  while True:
    yield a

    a += b
    a, b = b, a

for n in Fibonacci():
  raw_input(n)

Need Your Help

Instantiating A Singleton Class

iphone objective-c cocoa-touch

I have created a singleton class to keep track of my data on my iPhone app. I know singleton's only need to be instantiated once, but what is the best place to instantiate it? Should this be done i...

MSVC: what compiler switches affect the size of structs?

c++ struct alignment visual-c++ sizeof

I have two DLLs compiled separately, one is compiled from Visual Studio 2008 and one is a mex file compiled from matlab.