def search_namecard():
find_IG = input("The IG of the person you are looking for : ")
with open('memberinfo_.txt') as f:
datafile = f.readlines()
for line in datafile:
if find_IG in line:
return line
return False
while True:
print("INSERT(1), SEARCH(2), LIST(3), MODIFY(4), DELETE(5), EXIT(0)")
menu = get_menu()
if menu==1:
new_card = get_namecard_info()
with open("memberinfo_.txt", mode='a') as f:
f.write(new_card.printCard())
namecard_list.append(new_card)
elif menu==2:
if search_namecard() != True :
print(line)
else:
print("Not Found")
我编写了一个地址簿程序,它可以接收个人信息并将其存储在一个txt文件中。我试图添加一个搜索函数,但我正在使用readlines()函数。当我在地址簿中找到Instagram ID时,我想显示该人的信息,但我很好奇如何从函数中返回'line'变量。
输入图片描述
从函数返回line作为没有名称的值。您需要将该值保存在某个地方,以便像这样使用:
search_result = search_namecard()
if search_result:
print(search_result)
else:
print("Not found")
您需要将函数的返回值存储在if
子句之外的局部变量中,以便稍后可以打印它。像这样
while True:
print("INSERT(1), SEARCH(2), LIST(3), MODIFY(4), DELETE(5), EXIT(0)")
menu = get_menu()
if menu==1:
new_card = get_namecard_info()
with open("memberinfo_.txt", mode='a') as f:
f.write(new_card.printCard())
namecard_list.append(new_card)
elif menu==2:
line = search_namecard()
if line:
print(line)
else:
print("Not Found")
这里你可以在if
中直接使用line
,因为它返回的任何字符串(除了空字符串)都将假设一个真值。