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
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 + l = 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)