嵌套的 if 语句只返回 else 语句,除非选择了第一个值 | python

nested if statement is only returning the else statement unless first value is chosen | python

我正在做一个作业,一切都很顺利,除了我最后的 if/else 语句默认为 else 块,除非我输入我要检查的第一个值,我想我明白为什么但我不能'不要想办法阻止它。但是,当我 运行 没有 else 块的程序时,输出完全没问题。

输入文件:

LE1 Leicester
LE2 Oadby,Knighton,Highfields,Aylestone
LE3 Braunstone,Glenfield,Groby Road
LE4 BeaumontLeys,Belgrave,Birstall,Thurmaston
LE5 Hamilton,ThurnbyLodge,Evington

代码:

def area3(filename):
    f = open(filename, "r")
    aList = list()
    bList = list()

    for line in f:
        line = line.strip()
        f = line.split("\t")
        aList.append(f)

    for line in aList:
        for i in line[1:]:
            i = i.split(",")
            bList.append(i)

    for i in range(0, len(aList)):
        del aList[i][1]
        aList[i].append(bList[i])

    for j in aList:
        for x in j[1]:
            print(j[0], x)
    print("")

    x = input("Enter the name of the suburb to get its postcode: ")
    x = x.capitalize()

    for i in aList:
        for j in i[1]:
            if x == j:
                return "The postcode is: " + i[0]
            else:
                return "Not Found"

print(area3(input("Input filename: ")))

else 块的输出:

Input filename: postcode.txt
LE1 Leicester
LE2 Oadby
LE2 Knighton
LE2 Highfields
LE2 Aylestone
LE3 Braunstone
LE3 Glenfield
LE3 Groby Road
LE4 BeaumontLeys
LE4 Belgrave
LE4 Birstall
LE4 Thurmaston
LE5 Hamilton
LE5 ThurnbyLodge
LE5 Evington

Enter the name of the suburb to get its postcode: evington
Not Found

没有 else 块的输出:

Input filename: postcode.txt
LE1 Leicester
LE2 Oadby
LE2 Knighton
LE2 Highfields
LE2 Aylestone
LE3 Braunstone
LE3 Glenfield
LE3 Groby Road
LE4 BeaumontLeys
LE4 Belgrave
LE4 Birstall
LE4 Thurmaston
LE5 Hamilton
LE5 ThurnbyLodge
LE5 Evington

Enter the name of the suburb to get its postcode: evington
The postcode is: LE5

如能解决此问题,我们将不胜感激。

将最后一部分更改为 "Not found" 仅在列表完全迭代后返回。

for i in aList:
        for j in i[1]:
            if x == j:
                return "The postcode is: " + i[0]

return "Not Found"