Ali Abdulla
Ali Abdulla

Reputation: 9

Why does my Python script run forever?

Here is the code:

numbers = [1, 2]
while new < 1000:
    new = 0
    x = int(len(numbers) - 1)
    new = numbers[x] + numbers[x-1]
    if new % 2 == 0:
        numbers.append(new)
    new += 1
print sum(numbers)

What did I do wrong? Criticism is welcome. Thanks for your time.

Upvotes: 0

Views: 778

Answers (3)

Joseph Farah
Joseph Farah

Reputation: 2534

Every time you add one to the variable new in your loop, you set it back to 0 when you reiterate the loop! This means that new will never reach 1000--it will continue forever in the loop.

To fix this, move the initialization of new outside of the loop.

Upvotes: -1

Anand S Kumar
Anand S Kumar

Reputation: 90889

This is basically because of the following condition -

if new % 2 == 0:

coupled with the line - new=number[x] + number[x-1] at the start of the loop.

The first fibonacci number you calculate is 3 , because of the above condition , it is never actually added to number , and hence in every loop you are again calculating the same 1+2 , since number is never actually changed.

The issue is not because of the line - new=0 at the start of the loop like other answer are explaining (that line has no effect at all , you can remove it and see same results).

If your aim is to get the list of all even fibonacci numbers, then you can do -

numbers = [2]
a, b = 1, 2
while b < 1000:
    x = int(len(numbers) - 1)
    a, b = b, a+b
    if b % 2 == 0:
        numbers.append(b)
print sum(numbers)

Demo -

>>> numbers = [2]
>>> a, b = 1, 2
>>> while b < 1000:
...     x = int(len(numbers) - 1)
...     a, b = b, a+b
...     if b % 2 == 0:
...         numbers.append(b)
...
>>> print(sum(numbers))
798

Upvotes: 2

AI Generated Response
AI Generated Response

Reputation: 8835

The problem is that nothing really gets updated.

numbers = [1, 2]
while new < 1000:
    new = 0  #you're resetting new here
    x = int(len(numbers) - 1)
    new = numbers[x] + numbers[x-1] # first iteration, gives 3
    if new % 2 == 0:  # 3 % 2 != 0, so it doesn't get run
        numbers.append(new)
    new += 1 # great, new is now 1.
print sum(numbers)

Every iteration of the loop runs like this because nothing ever changes. If you wanted to do fibonacci, you would do something like this

numbers = [1, 2]
for _ in range(1000)
    n = numbers[-1] + numbers[-2] # use negative indices to count from the end.
    numbers.append(n)
print sum(numbers) # sum of fibonacci I guess

Upvotes: 1

Related Questions