Search code examples
pythonloopsenter

Python indentation mystery


Why am I getting the following error? The last print statement should not be a part of the while loop.

>>> while n>= 0:
...     n = n-1
...     print(n)
... print ("TO A!!")
  File "<stdin>", line 4
    print ("TO A!!")
        ^
SyntaxError: invalid syntax

Solution

  • You need to press enter after your while loop to exit from the loop

    >>> n = 3
    >>> while n>=0:
    ...     n = n-1
    ...     print (n)
    ...                         # Press enter here
    2
    1
    0
    -1
    >>> print ("To A!!")
    To A!!
    

    Note:- ... implies that you are still in the while block