【问题标题】:How to resolve the error for the below Python code Error : IndentationError: expected an indented block如何解决以下 Python 代码的错误错误:IndentationError: expected an indented block
【发布时间】:2020-07-27 17:07:25
【问题描述】:
# Python 3 implementation of the approach 

# Linearly search x in arr[]. If x is present 
# then return the index, otherwise return -1 
 
 def search(arr, n, x): 
 for i in range(n): 
     if arr[i] == x: 
        return i 
 return -1

# Driver Code 
arr = [1, 10, 30, 15] 
 x = 30
 n = len(arr) 
print(x, "is present at index",search(arr, n, x)) 

如何解决上述 Python 代码的错误 Error : IndentationError: expected an indented block 此代码旨在检查并返回数组值。

【问题讨论】:

  • Python 使用缩进(每行开头的空格)来了解哪些代码组合在一起。因此,for i in range(n) 需要比def search 缩进更多。此外,x = 30 不允许比arr = ... 缩进更多
  • 你应该学习python语法的基础(以及缩进,这是python的基础)。在你的情况下。 def 从第 2 列开始(应该从第 1 列开始),还有驱动程序代码:它都应该从第 1 列开始
  • @Ajay 我已经更新了你的代码并解决了缩进错误
  • 查看this doc 了解 Python 和缩进
  • @UmairMubeen 谢谢,我现在可以编译了。

标签: python algorithm pycharm


【解决方案1】:

在编写 python 代码时,你应该遵循基本的缩进。 参考https://docs.python.org/2.0/ref/indentation.html

def search(arr, n, x): 
 for i in range(n): 
     if arr[i] == x: 
        return i 
 return -1

# Driver Code 
arr = [1, 10, 30, 15] 
x = 30
n = len(arr) 
print(x, "is present at index",search(arr, n, x)) 

【讨论】:

  • 这不应该是答案,因为您应该解释出现缩进错误的位置
猜你喜欢
  • 1970-01-01
  • 2020-02-18
  • 1970-01-01
  • 1970-01-01
  • 2021-09-15
  • 1970-01-01
  • 1970-01-01
  • 2021-09-09
  • 1970-01-01
相关资源
最近更新 更多