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

时间:2015-11-19 03:24:40

标签: python hash

我有这个很长的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 个答案:

答案 0 :(得分:3)

555-5555之类的电话号码不是有效的整数,因此请将其保留为文字。

menu()内,您拨打menu(),呼叫menu()等。这是递归。当您选择3时,请离开上一个menu()并返回上一个menu()

修改

btw:您必须在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?: "))