Python实战1——address_book.py

本文介绍了一个使用Python实现的简易地址簿程序,通过简单的命令行交互即可完成联系人的添加、删除、修改、查找及打印等功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# 地址簿程序

import pickle as p
import sys

class Person:       #实际上不用类也可实现
    def __init__(self,name,address):
        self.name=name
        self.address=address
    def __Print__(self):
        print('%s 的地址为:%s'%(self.name,self.address))

book={}
filename='MyAddressBook.txt'
try:
    f=open(filename,'rb')
    book=p.load(f)
    f.close
except EOFError:     
    pass
#如果f为空的话会报错,实际上影响不大,所以这里跳过

print('-——————————————-')
print('操作编号:')
print('1->添加联系人\n2->删除联系人')
print('3->修改联系人\n4->查找联系人')
print('5->打印当前地址列表\n其他->保存文件')
print('-——————————————-')
while True:
    sel=input('请选择要进行的操作:')
    if sel=='1':
        name=input('>输入联系人的姓名:')
        address=input('>输入联系人的地址:')
        book[name]=address
        print('已添加%s!'%name)
    elif sel=='2':
        name=input('>输入联系人的姓名:')
        if name in book:
            del book[name]
        else:
            print('该联系人不存在!')    
        print('已删除%s!'%name)
    elif sel=='3':
        name=input('>输入联系人的姓名:')
        address=input('>重新输入联系人的地址:')
        book[name]=address
        print('已修改%s!'%name)
    elif sel=='4':
        name=input('>输入联系人的姓名:')
        if name in book:
            print('%s 的地址为:%s'%(name,book[name]))
        else:
            print('该联系人不存在!')
    elif sel=='5':
        if 0==len(book):
            print('地址簿是空的呢!')
        else:
            print('*****************')
            print('>>>>>地址列表<<<<\n')
            for name,address in book.items():
                print('%s:%s'%(name,address))
            print('\n*****************')
    else:
        break

f=open(filename,'wb')
p.dump(book,f)
f.close
print('保存完成!')

f=open(filename,'rb')           
b=p.load(f)
f.close
#这个地方加这几行代码,是因为不加的话会出现问题:
#当f为空之后,下一次运行就算输入数据也不会被保存。
#不知道为什么会这样。

sys.exit()
def display_menu(): """Display the main menu options.""" print("Address Book Menu") print("1. Add a contact") print("2. View all contacts") print("3. Search for a contact") print("4. Delete a contact") print("5. Exit") def add_contact(address_book): print("Add New Contact") name = input("Enter contact name: ").strip() if not name: print("Error: Name cannot be empty!") return if any(contact['name'].lower() == name.lower() for contact in address_book): print(f"Error: Contact '{name}' already exists!") return phone = input("Enter phone number: ").strip() email = input("Enter email address: ").strip() contact = { 'name': name, 'phone': phone, 'email': email } address_book.append(contact) print(f"\nSuccess: Contact '{name}' added!") def view_contacts(address_book): print("All Contacts") if not address_book: print("No contacts found.") return print("{:<20} {:<15} {:<30}".format('Name', 'Phone', 'Email')) # Print each contact for contact in address_book: print("{:<20} {:<15} {:<30}".format( contact['name'], contact['phone'], contact['email'] )) print(f"Total contacts: {len(address_book)}") def search_contact(address_book): print("Search Contacts") search_term = input("Enter search term: ").strip().lower() if not search_term: print("Error: Search term cannot be empty!") return matches = [ contact for contact in address_book if search_term in contact['name'].lower() ] if not matches: print("\nNo matching contacts found.") return print(f"Found {len(matches)} matching contacts:") print("{:<20} {:<15} {:<30}".format('Name', 'Phone', 'Email')) for contact in matches: print("{:<20} {:<15} {:<30}".format( contact['name'], contact['phone'], contact['email'] )) def delete_contact(address_book): print("Delete Contact") name = input("Enter name to delete: ").strip() if not name: print("Error: Name cannot be empty!") return for i, contact in enumerate(address_book): if contact['name'].lower() == name.lower(): del address_book[i] print(f"\nSuccess: Contact '{contact['name']}' deleted!") return print("\nError: Contact not found.") def main(): address_book = [] while True: display_menu() choice = input("\nEnter your choice : ").strip() if not choice.isdigit(): print("\nInvalid selection. Please enter a number from 1 to 5.") continue choice = int(choice) if choice == 1: add_contact(address_book) elif choice == 2: view_contacts(address_book) elif choice == 3: search_contact(address_book) elif choice == 4: delete_contact(address_book) elif choice == 5: print("\nExiting program. Goodbye!") break else: print("\nInvalid selection. Please choose 1-5.") continue if __name__ == "__main__": main() 生成这个程序的测试日志
最新发布
06-24
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值