Python indentation mystery

2020-04-30 01:50发布

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

3条回答
淡お忘
2楼-- · 2020-04-30 01:54

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

查看更多
不美不萌又怎样
3楼-- · 2020-04-30 01:56

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]: 
查看更多
Explosion°爆炸
4楼-- · 2020-04-30 02:00

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.

查看更多
登录 后发表回答