首页 文章

在txt文件中添加新的联系信息

提问于
浏览
1

我有这个很长的python代码,我无法完成或修复它,我需要帮助 .

首先,我有这些代码 -

这只会显示菜单,我创建了几个def函数 . 一种是创建数据并保存到txt文件,另一种是使用散列函数来分割名称 . 在txt文件中创建数据时联系信息 . 最后,在一个while循环中,我必须以某种方式调出菜单代码,这是我被卡住的地方,或者我可能需要修复整个事情 . 此外,当我将电话号码设置为555-5555时,它会出错 . 我如何输入这个值的数字?

def menu():
    print("Contact List Menu:\n")
    print("1. Add a Contact")
    print("2. Display Contacts")
    print("3. Exit\n")
menu()
choice = int(input("What would you like to do?: "))

def data():
    foo = open("foo.txt", "a+")
    name = input("enter name: ")
    number = int(input("enter the number: "))
    foo.write(name + " " + str(number))
foo.close()


def contact():
    data = open("foo.txt")
    file = {}
    for person in data:
        (Id, number) = person.split()
        file[number] = Id
data.close()

while choice !=3:
    if choice == 1:
        print(data())
    if choice ==2:
        print(data())
    menu()
    choice = int(input("What would you like to do?: "))

似乎程序永远不会停止,我必须使用菜单中的选项3退出程序 .

1 回答

  • 3

    555-5555 这样的电话号码不是有效的整数,所以请将其保留为文本 .

    menu() 内你调用 menu() ,它调用 menu() 等 . 它是递归 . 当您选择 3 时,您将离开最后 menu() 并返回上一个 menu() .


    EDIT:

    顺便说一句:你必须在 write 中添加"\n"

    def menu():
        print("Contact List Menu:\n")
        print("1. Add a Contact")
        print("2. Display Contacts")
        print("3. Exit\n")
    
    def data():
        foo = open("foo.txt", "a+")
        name = input("enter name: ")
        number = int(input("enter the number: "))
        foo.write(name + " " + str(number) + "\n") # new line
        foo.close()
    
    def contact():
        data = open("foo.txt")
        for person in data:
            name, number = person.split()
            print(name, number)
        data.close()
    
    #----------------
    
    menu()
    choice = int(input("What would you like to do?: "))
    
    while choice !=3:
    
        if choice == 1:
            data()
        if choice == 2:
            contact()
    
        menu()
        choice = int(input("What would you like to do?: "))
    

相关问题