我正在做一个作业,一切都进行得很顺利,除了我的最终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”
相关问题 更多 >
编程相关推荐