首页 > 解决方案 > 我不知道如何返回和打印函数结果。(我正在做一个python通讯录程序)

问题描述


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' 变量从函数中返回。

在此处输入图像描述

标签: pythonfunctionreturnreadlines

解决方案


您从函数中返回 line 作为没有名称的值。您需要将值保存在某处才能像这样使用它:

search_result = search_namecard()
if search_result:
    print(search_result)
else: 
    print("Not found")

推荐阅读