Why does this Spam Code run unlimited times?

Viewed 340

Got an exam in python in two days, pretty basic stuff. This is the code given in an exercise

spam = 0
while spam < 5:
    print('Hello, world.')
spam = spam + 1

I would have expected it to run until it hits 5 (so with the +1 given in the last line 2 times) But the answer is "Unlimited times".

Anyone knows why? :) Is ir because there is no elif condition in this example?

2 Answers

In python, indentation matters. Try this:

spam = 0
while spam < 5:
    print('Hello, world.')
    spam = spam + 1

If you don't ident the line spam = spam + 1 Python will interpret it as being out of the while block, therefore it is not executed and it stays on an endless loop.

Let's break down the code line by line.

First you have

spam = 0

This sets the variable spam equal to the value 0. And it will always stay that value until explicitly changed by the code.

Then we have a while loop

while spam < 5:
    print('Hello, world.')

This literally means while the value of spam is less than 5 keep calling print('Hello World'). However, spam is equal to 0, so it being smaller than 5 is true and will always be true. This loop also does not change the value so the loop will run indefinitely.

Finally, we have

spam = spam + 1

This staments increments spam by 1, but the problem is that this statement is never reached! I.e. it is placed after a loop that runs indefinitely!

Related