电话菜单-Python 3
我正在尝试制作一些手机菜单项目,包括查看、添加和删除联系人。哪种方法更好,是将联系人添加到字典中,还是创建新文件并从中写入/读取 我尝试了第一种方法-我已经将新联系人添加到空字典中,然后我尝试使用查看选项查看它,但字典仍然是空的 这是我的“项目”的第一个示例: 因此,这种方法不起作用,我还尝试写入text.txt文件电话菜单-Python 3,python,python-3.x,dictionary,Python,Python 3.x,Dictionary,我正在尝试制作一些手机菜单项目,包括查看、添加和删除联系人。哪种方法更好,是将联系人添加到字典中,还是创建新文件并从中写入/读取 我尝试了第一种方法-我已经将新联系人添加到空字典中,然后我尝试使用查看选项查看它,但字典仍然是空的 这是我的“项目”的第一个示例: 因此,这种方法不起作用,我还尝试写入text.txt文件 condition = True while condition == True: print("Menu") print("contacts") pr
condition = True
while condition == True:
print("Menu")
print("contacts")
print("Add contacts")
print("Remove contacts")
phone_contacts = {}
def contacts(x):
for item in dict(x):
print(item, x[item])
def add_contacts(x):
new_key = input("Enter a name\n")
new_value = input("Enter a number\n")
text = "%s - %d" % (new_key, int(new_value))
savefile = open("text.txt", "w")
savefile.write(text)
savefile.read(text)
savefile.close()
def remove_contacts(x):
for item in dict(x):
print(item)
removing_contact = input("Enter a contact to remove\n")
if removing_contact in x:
del x[removing_contact]
print("Contact has been deleted!")
else:
print("There is no '%s\' contact!") % (removing_contact)
choose = input("Select option")
if choose == "1":
print(contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
elif choose == "2":
print(add_contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
elif choose == "3":
print(remove_contacts(phone_contacts))
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
else:
print("You didn't type anything!")
choose_2 = input("End/Back to MENU").lower()
if choose_2 == "end":
break
elif choose_2 == "menu":
pass
它也不起作用
在这两种情况下,我做错了什么?我应该选择哪条路,第一条还是第二条
顺便说一句,我会很感激任何提示,我可以如何纠正我的代码,即使这些提示不涉及的问题 在这两个选项中,每次迭代都会覆盖字典。您应该在循环外只初始化它一次。对于第一个选项,它将如下所示:
phone_contacts = {} # this line moved from inside the loop
while condition == True:
print("Menu")
print("contacts")
print("Add contacts")
print("Remove contacts")
# the line deleted from here
# ...
在这两个选项中,每次迭代都会覆盖字典。您应该在循环外只初始化它一次。对于第一个选项,它将如下所示:
phone_contacts = {} # this line moved from inside the loop
while condition == True:
print("Menu")
print("contacts")
print("Add contacts")
print("Remove contacts")
# the line deleted from here
# ...
您应该在主while(True)之前和之外定义所有函数。您应该将ifs块转换为接收输入的函数。 您应该明确哪个键是哪个选项
list1=['a','b','c']
def operateList(number):
if number == '3':
try: list1.remove(input('Type what you want to remove:'))
except: print('not in List')
elif number == '2':
list1.append(input('Type in what you want to add:'))
list1.sort()
elif number == '1':
print(list1)
while(True):
print('1: List')
print('2: Add')
print('3: Remove')
operateList(input('Input option number:'))
您应该在主while(True)之前和之外定义所有函数。您应该将ifs块转换为接收输入的函数。 您应该明确哪个键是哪个选项
list1=['a','b','c']
def operateList(number):
if number == '3':
try: list1.remove(input('Type what you want to remove:'))
except: print('not in List')
elif number == '2':
list1.append(input('Type in what you want to add:'))
list1.sort()
elif number == '1':
print(list1)
while(True):
print('1: List')
print('2: Add')
print('3: Remove')
operateList(input('Input option number:'))
首先,您必须声明phone_联系人以及循环之外的功能 第二,条件中存在冗余 创建一个文件来存储联系人的想法很棒。我会将其保存为
.json
文件,因为它非常易于处理
这是我已经尽可能重构的代码
import json
phone_contacts = {}
def print_contacts():
if not phone_contacts:
print("Empty list.")
return
for name, number in sorted(phone_contacts.items()):
print(name, number) # explicit is better than implicit
def add_contact():
name = input("Enter a name\n")
number = input("Enter a number\n")
if name and number:
phone_contacts[name] = number
print("Contact added: {0}, {1}".format(name, number))
def remove_contacts():
print_contacts()
removing_contact = input("Enter a contact to remove\n")
if removing_contact in phone_contacts:
del phone_contacts[removing_contact]
print("Contact has been deleted!")
else:
print("There is no '%s' contact!") % (removing_contact)
def load_contacts():
global phone_contacts
try:
with open('contacts.json', 'r') as file:
phone_contacts = json.load(file)
except (ValueError, OSError): # OSError catches FileNotFoundError
phone_contacts = {}
def save_contacts():
with open('contacts.json', 'w+') as file:
json.dump(phone_contacts, file)
load_contacts()
while True:
print("0. Exit")
print("1. Menu")
print("2. Add contact")
print("3. Remove contacts")
choose = input("Select option: ")
if choose == "0":
print("Exiting program...")
break
elif choose == "1":
print_contacts()
elif choose == "2":
add_contact()
elif choose == "3":
remove_contacts()
else:
print("You didn't type a valid option!")
# moved this block out as it's common to all options
choose_2 = input("End/Back to MENU\n").lower()
if choose_2 == "end":
break
# even if user typed anything different of menu
# he/she would continue in the loop so that else was needless
save_contacts()
还请注意,您不需要将电话联系作为参数传递,因为它是全局的
我添加了load和save contacts函数,这很容易理解,即使您没有使用JSON的经验
有很多事情要问,所以如果你有疑问,想问我,请放心!;) 首先,您必须声明电话联系人和环路外的功能 第二,条件中存在冗余 创建一个文件来存储联系人的想法很棒。我会将其保存为
.json
文件,因为它非常易于处理
这是我已经尽可能重构的代码
import json
phone_contacts = {}
def print_contacts():
if not phone_contacts:
print("Empty list.")
return
for name, number in sorted(phone_contacts.items()):
print(name, number) # explicit is better than implicit
def add_contact():
name = input("Enter a name\n")
number = input("Enter a number\n")
if name and number:
phone_contacts[name] = number
print("Contact added: {0}, {1}".format(name, number))
def remove_contacts():
print_contacts()
removing_contact = input("Enter a contact to remove\n")
if removing_contact in phone_contacts:
del phone_contacts[removing_contact]
print("Contact has been deleted!")
else:
print("There is no '%s' contact!") % (removing_contact)
def load_contacts():
global phone_contacts
try:
with open('contacts.json', 'r') as file:
phone_contacts = json.load(file)
except (ValueError, OSError): # OSError catches FileNotFoundError
phone_contacts = {}
def save_contacts():
with open('contacts.json', 'w+') as file:
json.dump(phone_contacts, file)
load_contacts()
while True:
print("0. Exit")
print("1. Menu")
print("2. Add contact")
print("3. Remove contacts")
choose = input("Select option: ")
if choose == "0":
print("Exiting program...")
break
elif choose == "1":
print_contacts()
elif choose == "2":
add_contact()
elif choose == "3":
remove_contacts()
else:
print("You didn't type a valid option!")
# moved this block out as it's common to all options
choose_2 = input("End/Back to MENU\n").lower()
if choose_2 == "end":
break
# even if user typed anything different of menu
# he/she would continue in the loop so that else was needless
save_contacts()
还请注意,您不需要将电话联系作为参数传递,因为它是全局的
我添加了load和save contacts函数,这很容易理解,即使您没有使用JSON的经验
有很多事情要问,所以如果你有疑问,想问我,请放心!;) 谢谢你努力帮助我!您能告诉我为什么在代码中使用这个“try/except”方法吗?我试图找到一些关于它的信息,但我不明白。我应该在什么时候使用它,目的是什么?try/except用于处理程序中的错误。当程序执行某些可能以意外方式运行的操作时,应该使用它,以避免此异常导致应用程序崩溃。例如,在本例中,我使用try/except来读取可能不存在的文件中可能不存在的内容。因此,当异常引发时,代码只会创建一个空字典。尝试删除Try/except语句,并在目录中运行包含或不包含contacts.json文件的代码。也谢谢你的努力来帮助我!您能告诉我为什么在代码中使用这个“try/except”方法吗?我试图找到一些关于它的信息,但我不明白。我应该在什么时候使用它,目的是什么?try/except用于处理程序中的错误。当程序执行某些可能以意外方式运行的操作时,应该使用它,以避免此异常导致应用程序崩溃。例如,在本例中,我使用try/except来读取可能不存在的文件中可能不存在的内容。因此,当异常引发时,代码只会创建一个空字典。尝试删除Try/except语句,并在目录中运行包含或不包含contacts.json文件的代码。阿尔索