
可以使用 Python 中的字典(dictionary)来实现一个简单的增删改查程序。具体实现步骤如下:
创建一个空字典用于存储数据。
通过循环菜单的方式,让用户可以选择添加、修改、删除、显示、退出等功能。
根据用户的选择执行相应的 *** 作,例如添加数据就让用户输入键值对,修改数据就让用户选择要修改的键和新值,删除数据就让用户选择要删除的键,显示数据就输出整个字典,退出就结束程序。
下面是一个简单的代码示例:
data = {} # 创建空字典用于存储数据
while True:
print('请选择 *** 作:')
print('1. 添加数据')
print('2. 修改数据')
print('3. 删除数据')
print('4. 显示数据')
print('5. 退出程序')
choice = input('请输入选项:')
if choice == '1':
key = input('请输入键:')
value = input('请输入值:')
data[key] = value
print('添加成功!')
elif choice == '2':
key = input('请输入要修改的键:')
if key in data:
value = input('请输入新值:')
data[key] = value
print('修改成功!')
else:
print('该键不存在!')
elif choice == '3':
key = input('请输入要删除的键:')
if key in data:
del data[key]
print('删除成功!')
else:
print('该键不存在!')
elif choice == '4':
print(data)
elif choice == '5':
print('谢谢使用,再见!')
break
else:
print('输入错误,请重新选择。')
这个程序简单易懂,可以根据自己的需要进行修改和扩展。
#第二题:
#没有办法写缩进,看不了下载图片
dictionary = {}
while True:
response = str(input("您要查询、添加、删除还是退出字典: "))
if response == "查询":
search_response = str(input("您要查询什么: "))
if search_response in dictionary:
print(search_response + ": " + dictionary[search_response])
elif response == "添加":
add_response_name = str(input("您要创建新词的名字: "))
if add_response_name in dictionary:
add_conform = str(input("单词已存在!您要更改吗(要/不要): "))
if add_conform == "要":
add_response_value = str(input("您要创建新词的意思: "))
dictionary[add_response_name] = add_response_value
print("新词已创建!")
else:
pass
add_response_value = str(input("您要创建新词的意思: ")
dictionary[add_response_name] = add_response_value
print("新词已创建!")
elif response == "删除":
delete_response = str(input("您要删除哪个词: "))
if delete_response not in dictionary:
print("该词不在词典内!")
else:
del dictionary[delete_response]
print("该词已删除!")
else:
print("程序已退出!")
break
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)