我的编码在这里有什么问题?

时间:2018-05-17 01:18:45

标签: python-3.x

enter image description here

fruitList = ["strawberry", "apple", "banana"]
searchFor = "apple"

def findIndex(el,fruitList):
    wordIndex = None
    for(ind, el) in enumerate(fruitList):
        if el == searchFor:
            wordIndex = ind
    return wordIndex
print("the index corresponding to", searchFor, "is", wordIndex)

问题描述: 上面的代码是我的python类中的一个消费税。我们想要得到的是打印出列表中单词的所有索引。但不知何故,当我把它打印出来时,它会说出名字" wordIndex"没有定义。所以我想知道为什么我的代码错了?我错过了什么吗?

我非常感谢那些投入宝贵时间回答我的问题的人!

2 个答案:

答案 0 :(得分:0)

为了将来参考,您应该将代码作为文本发布,而不是作为图像发布。单击编辑器中的{}图标。

您将public override void ViewDidLoad() { base.ViewDidLoad(); if (dateOutput != null) { dateInput.Text = dateOutput; } } 放在wordIndex = None函数内。这很好,但是您必须明白,当您执行此操作时,findIndex仅对wordIndex内的代码可见。

您还必须致电findIndex来运行代码,即写findIndex。放置findIndex(someVariable, someList)表示对findIndex的函数调用将计算为wordIndex的值。

更正后的版本:

return wordIndex

注意在最后一个print语句中调用findIndex。 fruitList = ["strawberry", "apple", "banana"] searchFor = "apple" def findIndex(el, fruitList): wordIndex = None for (ind, el) in enumerate(fruitList): if el == searchFor: wordIndex = ind return wordIndex print("the index corresponding to", searchFor, "is", findIndex("",fruitList)) 被评估为wordIndex的值。

答案 1 :(得分:0)

您的缩进不正确(查看您粘贴的示例)。

fruitList = ["strawberry", "apple", "banana"]
searchFor = "apple"

def findIndex(el,fruitList):
    wordIndex = None
    for (ind, el) in enumerate(fruitList):
        if el == searchFor:
            wordIndex = ind

    return wordIndex

此代码没有语法错误。

但您可能希望将searchFor作为参数传递给您的函数:

fruitList = ["strawberry", "apple", "banana"]

def findIndex(element, list):
    wordIndex = None
    for (ind, el) in enumerate(fruitList):
        if el == element:
            wordIndex = ind

    return wordIndex

print(findIndex("banana", fruitList))

请注意,函数参数名称与更多全局变量名称无关。否则它会给你变量范围的问题。例如,在findIndex()函数中,有一个' fruitList'在全局范围内,但也在本地范围内(对函数)。本地范围优先。

相关问题