Python indentation mystery

后端 未结 3 2012
别跟我提以往
别跟我提以往 2021-01-27 00:47

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

>>> while n>= 0:
.         


        
相关标签:
3条回答
  • 2021-01-27 01:29

    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.

    0 讨论(0)
  • 2021-01-27 01:32

    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

    0 讨论(0)
  • 2021-01-27 01:43

    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]: 
    
    0 讨论(0)
提交回复
热议问题