Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does this Spam Code run unlimited times?

Tags:

python

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?

like image 335
Metty Avatar asked Jan 23 '26 22:01

Metty


2 Answers

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!

like image 64
WiseDev Avatar answered Jan 25 '26 10:01

WiseDev


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.

like image 38
Lucas Wieloch Avatar answered Jan 25 '26 11:01

Lucas Wieloch



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!