python语法有什么问题?

时间:2019-04-12 00:11:34

标签: python-3.x

  

我只是针对离散结构和算法类进入python>,由于某种原因,我的语法出现错误,但我没有   了解为什么您可以协助解决此错误:

     

第10行

     

i = i + 1

     

IndentationError:unindent与任何外部缩进级别都不匹配   也是出于某种原因我的代码无法打印

#linear search algorithm
 def search(list1, n):
    i = 0

    while i < len(list1):
         if list1[i] == n:
            print("found now")
            return True
        i = i + 1

    return False


list1 = [1,5,9,3,4,6]
n = 6

if search(list1, n):
    print("found")
else:
    print("not found")

2 个答案:

答案 0 :(得分:0)

正如其他人在您的评论中提到的那样,您的缩进很奇怪。 Pythonic代码对于每条缩进/未缩进的行都倾向于使用4个空格。

要线性搜索列表数据结构中的元素,可以使用in关键字。这是功能上的代码,但行数较少:

list1 = [1,5,9,3,4,6]
n = 6

if n in list1:
    print("found") # Indent 4 spaces
else: # Unindent 4 spaces
    print("not found") # Indent 4 spaces

现在输入您的代码:

 def search(list1, n): # Careful! You have an extra space here.
    i = 0 # Indent 3 spaces

    while i < len(list1):
         if list1[i] == n: # Indent 5 spaces
            print("found now") # Indent 3 spaces
            return True
        i = i + 1 # Unindent 4 spaces

    return False # Unindent 4 spaces

因此,一开始要删除多余的空间,并每次将其固定为4个空间。

注意:in关键字也可以用于其他可迭代对象(元组,字典,集合等),或类中具有__contains__的对象。

由于这是一门课程,他们可能只是希望您像以前那样通过使用索引变量(例如,...中的 i )来熟悉线性搜索,但是python已经在后台使用in关键字为您完成了此操作。

答案 1 :(得分:0)

Python是一种“制表符”(缩进)敏感的编程语言,请确保在使用function \时\如果\ while循环等,请删除\添加制表符\空格

建议您使用IDE工具检测语法错误(在我的情况下,我正在使用Visual Studio 2017),

IDE show which line you have make mistake

您的代码应如下所示,其中tab \ space对齐

enter image description here