I can't run a while loop in Python 3.9

189 Views Asked by At

So I am a beginner in python and I have found a book about its basics. The book is based on python 3.4. The book is trying to teach me while loops. When I try to enter the code which is:

counter = 5

while counter > 0: print ("Counter =", counter) counter = counter - 1

The book says the output should be:

Counter = 5
Counter = 4
Counter = 3
Counter = 2
Counter = 1

When I try to run the code, the idle gives me a message of invalid syntax and marking the c in 'counter = counter' red.

I tried fixing that by placing a comma before the word 'counter' and it worked, but when I re-ran the code, the same message popped up again but this time targeting the print command and marking its 'p' letter red.

I tried to solve that issue by placing a comma before the print command but it didn't work.

I tried writing the code with notepad++ but it also didn't work.

What should I do?

2

There are 2 best solutions below

2
kabooya On

Python syntax is white-space sensitive. Don't write things on one line. Do it like this:

counter = 5

while counter > 0: 
    print ("Counter =", counter) 
    counter = counter - 1
0
Peter Parker On

You need to spearate multiple commands with semicolon (";"):

counter = 5

while counter > 0: print ("Counter =", counter); counter = counter - 1

However, as kabooya stated, this is not the pythonic way. As you see, the correctly formatted source (in his answer) is much more readable.