Python indentation mystery

半城伤御伤魂 提交于 2019-12-20 04:32:16

问题


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

回答1:


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




回答2:


The default python shell works OK for typing but it really does not understand pasting from clipboard. The real solution is to install ipython, which is an advanced shell for python with many niceties:

% ipython3
Python 3.4.2 (default, Oct  8 2014, 13:08:17) 
Type "copyright", "credits" or "license" for more information.

IPython 2.3.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: n = 5

In [2]: while n >= 0:
   ...:     n = n-1
   ...:     print(n)
   ...: print ("TO A!!")
   ...: 
4
3
2
1
0
-1
TO A!!

In [3]: 



回答3:


I guess that the error shows up because python shell don't support that. It want you to do one thing in a time.! I do the same things in my python 2.7 shell and it said:

File "<pyshell#4>", line 4
    print 'to all'
                 ^
IndentationError: unindent does not match any outer indentation level

when I do the same thing in my python 3.4 shell, it said: unexpected indent.



来源:https://stackoverflow.com/questions/28525307/python-indentation-mystery

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!