While loop is always infinite

test_loop = 5
while test_loop > 0: print(‘Another loop!’)
test_loop = test_loop - 1
print(“Oh, at last, we ended our loop”)

whenever i run this code in my python console it can be stopped only with Ctr+C
it prints infinetly ‘another loop’
I even tried to change test_loop > 4 and wrote this code

test_loop = 0
while test_loop < 5: print(‘Another loop!’)
test_loop = test_loop + 1
print(“Oh, at last, we ended our loop”)

But the result is the same.
Here’s another code
some_list = [10, 20, 30, 40, 50]
i = 0
length = len(some_list)
while i < length: print(“at number”, i, “your code is”, some_list[i])
i = i + 1
it always print “at number 0 your code is 10”
Looks like i is always 0.

Python version 3.7. Code is written in VSCode 1.6.4.
What’s wrong? Is it the code, Python or IDE version?

Has to do with how your loop is built. Remember that indentation is very important in Python fro defining blocks of code. Because you have the print() on the same line as the while loop, that is considered its body. It is the same as writing:

test_loop = 5
while test_loop > 0: 
  print('another loop')
test_loop -= 1

Do you see the problem? test_loop -= 1 is outside of the loops body and so will never run, meaning test_loop never decrements, and the loop continues.

That’s correct!
It was all about identation! I didn’t know Python is so strict about it.
Turns out, when you use 'while loop, you have to type it correctly.
some_value = 0
while some_value < 5:
(here we have to add two tabs) print(“test loop #”, some_value)
(here we have to add another two tabs) some_value += 1
print(“we exited our loop after”, some_value, “itterations!”)

1 Like

My biggest dislike for the Python language is it’s indentation. I much prefer the more common brackets, but to each their own.
That said, Python is still an excellent language and I love it. Especially for writing short scripts.

1 Like

Thanks a lot for your comments :grinning:

1 Like