Python中While循环后的缩进错误

问题描述 投票:-3回答:3

我有以下功能,每当我尝试运行它时,我会收到一个Indentation Error

def fib(n):    
    # write Fibonacci series up to n
    """Print a Fibonacci series up to n."""
a, b = 0, 1
while a < n:
print a
a, b = b, a+b
 # Now call the function we just defined:
fib(2000)

错误信息:

print a
        ^
IndentationError: expected an indented block

如何解决python中的IndentationError错误?

python
3个回答
1
投票

您需要正确缩进代码。就像其他语言使用括号一样,Python使用缩进:

def fib(n):    
    # write Fibonacci series up to n
    """Print a Fibonacci series up to n."""
    a, b = 0, 1

    while a < n:
        print a
        a, b = b, a+b

1
投票

要解决此问题,您需要添加空格。你的代码必须是这样的:

def fib(n):    
# write Fibonacci series up to n
"""Print a Fibonacci series up to n."""
      a, b = 0, 1

      while a < n:

            print a

            a, b = b, a+b

 # Now call the function we just defined:
fib(2000)

0
投票

这只是因为语法。 while循环到达新行并给出Tab并开始写下面的语句。

>>> while a < 10:    *#this is your condition end with colon ':'*                             
...     print(a)      *#once come to new line press Tab button it will resolve problem*  

0
投票
def fib(n):    
a, b = 0, 1
while a < n:
    print (a, end=' ')
    a, b = b, a+b
    print()
    fib(1000)
© www.soinside.com 2019 - 2024. All rights reserved.