-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 错误?

4

4 回答 4

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
于 2013-05-04T08:26:26.253 回答
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)
于 2013-05-05T06:05:50.267 回答
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*  
于 2019-02-20T09:49:17.460 回答
0
def fib(n):    
a, b = 0, 1
while a < n:
    print (a, end=' ')
    a, b = b, a+b
    print()
    fib(1000)
于 2019-08-27T22:06:27.327 回答