我有这么长的 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 来退出程序。
最佳答案
555-5555
等电话号码不是有效的整数,因此请将其保留为文本。
在menu()
内部,你调用menu()
,它又调用menu()
,等等。这是递归。当您选择3
时,您将离开上一个menu()
并返回到上一个menu()
。
编辑:
顺便说一句:你必须在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?: "))
关于python - 在txt文件中添加新的联系信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33794719/