0

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
1
  • 8
    You don't modify k in the while loop. Commented Apr 13, 2012 at 22:44

5 Answers 5

3

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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)

Comments

2

Just move the line with k in it:

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

print l

Comments

0

You're not doing any changes to the k variable. Once you calculate the value of K, the code gets stock in the while loop because the value of k never changes, you simply keep appending the value of k to the list.

Comments

-1

not sure about python, but looks like you update the value of K ever also, not sure what is the scope of the while loop in python syntax.

Comments

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.