Home > Software engineering >  breaking out of a loop in python
breaking out of a loop in python

Time:06-23

>>> while True:
    ...    line = input('> ')
    ...    if line == 'done' :
    ...         break
    ...    print(line)
    ... print( 'Done!' )
      File "<stdin>", line 6
        print( 'Done!' )
        ^^^^^
    SyntaxError: invalid syntax**

For python 3 this code should give me a "Done!" response when the break statement "done" is reached. However, I keep getting a syntax error for the last line. I have tried to do it multiple ways and I can get the break order to work without the last statement, however, it never works where I include the last statement "print('Done!')" with the break statement done. I apologize, this is just simple code but I can't seem to get it to work. Ps, I fixed it to make it as I am supposed to be writing it, the while True statement was not supposed to be twice (my error in copying it here) along with the extra space on the fifth line. and I have tried

CodePudding user response:

It's not the language, it's your IDE. It is only expecting a single statement and the lines that are subordinate to it, i.e. indented. Once you've reached the end of the indenting it expects a blank line and doesn't know what to do when you try to give another statement.

If that same sequence were part of a file it would do exactly what you expect. If you put it all into a function, the whole function body will be indented and that would work too.

  • Related