Python绕过/忽略else语句



目的是不断提示用户输入并在csv文件中搜索该名称,返回它所在的行,如果该名称不在文件中,则将用户输入的名称的地址添加到文件中的新行。问题是else语句被完全忽略,脚本每次都运行这两个部分。

import csv
b = [None] * 2
while True:
a = input("Enter name: ")
with open("addresses.csv") as f_obj:
reader = csv.reader(f_obj, delimiter=":")
for row in reader:
if a in row:
print(row)
else:
with open("addresses.csv", "a+", newline="") as f:
writer = csv.writer(f, delimiter=":")
temp = input(f"Enter {a}'s address:")
b[0] = a
b[1] = temp
writer.writerow(b)

所需行为:

content of addresses.csv before running script: 
name:street1
```
user input: name
output: name:street1
user input: test
output: "Enter test's address: "
user input: street2
```
content of addresses.csv after running script: 
name:street1
test:street2

考虑每一行对应一个不同的条目。现在,在每一行上执行if-else语句。那么,假设你的文件是这样的:

Alice,Address1
Bob,Address2

如果我们要寻找Alice, for循环的第一次迭代将采用if路径。但是,由于我们没有停止搜索(使用类似break的东西),我们也移动到第二行。Alice不是Bob,所以我们选择else路径。注意,如果文件中有3个条目,我们将运行else语句两次。如果我们搜索Bob而不是Alice,也会出现类似的问题。

我建议的(未经测试的)修复如下:

import csv
b = [None] * 2
while True:
a = input("Enter name: ")
with open("addresses.csv") as f_obj:
reader = csv.reader(f_obj, delimiter=":")
found = False
for row in reader:
if a in row:
print(row)
found = True
break
if not found:
with open("addresses.csv", "a+", newline="") as f:
writer = csv.writer(f, delimiter=":")
temp = input(f"Enter {a}'s address:")
b[0] = a
b[1] = temp
writer.writerow(b)

相关内容

  • 没有找到相关文章