حالت آفلاین — محتوا از حافظهٔ کش نمایش داده می‌شود
همهٔ تمرین‌ها

دفترچه تلفن

تمرین آسان 6074 visibility link download flag trending_up پربازدید

یک برنامه دفترچه تلفن بنویسید که:

1. برنامه باید امکان اضافه کردن یک مخاطب جدید با نام و شماره تلفن را فراهم کند.

2. کاربر باید بتواند مخاطبان موجود را مشاهده و بین آنها جستجو کند.

3. کاربر باید بتواند مخاطبان موجود را ویرایش یا حذف کند.

این تمرین یه پروژه ست! یعنی پتانسیل اینو داره که خیلی بیشتر روش کار بشه بنابراین ایده اصلی رو از اینجا بردار و خودت بیشتر روش کار کن تا به یه تمرین بزرگتر تبدیل یشه
👨‍💻 12 ساعت قبل کاربر ناشناس این تمرین رو مشاهده کرد

پاسخ‌ها 17

class Phone:
    def __init__(self, phonename, phonenumber):
        self.name = phonename
        self.number = phonenumber

    def print(self):
        return f"{self.name} {self.number}"

phones = []

def seephone():
    for index, phone in enumerate(phones, 1):
        print(f"{index}. {phone.print()}")

while True:
    what = int(input("1.add 2.remove 3.edit 4.list : "))
    if what == 1:
        name = input("name: ")
        number = input("phone_number: ")

        phone = Phone(name, number)
        phones.append(phone)

        seephone()
    elif what == 2:
        seephone()
        number = int(input("name: "))
        phones.pop(number-1)

    elif what == 3:
        seephone()
        num = int(input("number: "))

        name = input("new_name: ")
        number = input("new_number: ")

        phone = phones[num-1]

        phone.name = name
        phone.number = number

    elif what == 4:
        seephone()
import os

class Contacts:
    def __init__(self, contact_name , phone_number):
        self.contact_name = contact_name
        self.phone_number = phone_number

    def show_contacts(self):
        print(f"name: {self.contact_name}")
        print(f"phone number: {self.phone_number}")

# checking if phone number is correct
def phone_number_checker(number):
    if len(number) != 11:
        return False
    else:
        if number.isdigit():
            return True
        else:
            return False


# adding new contact
def add_contact():
        name = input("contact's name: ")
        while 1:
            phone = input("contact's phone: ")
            if phone_number_checker(phone) == True:
                contact = Contacts(contact_name= name, phone_number=phone)
                contacts.append(contact)
                print(f"{name} added to your list")
                break
            else:
                print("phone number is not correct")


# showing contacts
def contacts_list():
    for i,contact in enumerate(contacts):
        print(i+1, end=". ")
        contact.show_contacts()

# update the contacts
def update_contact():
    contacts_list()
    number = int(input("pick a number to update: "))
    new_name = input("new name or enter: ")
    while 1:
        new_number = input("new number or enter: ")
        if phone_number_checker(new_number) == True or new_number == "":
            break
        else:
            print("phone number is not correct")
    contact = contacts[number-1]
    if new_number == "":
        contact.contact_name = new_name
    elif new_name == "":
        contact.phone_number = new_number
    else:
        contact.contact_name = new_name
        contact.phone_number = new_number
    print("contact updated successfully")


# removing contacts
def delete_contact():
    contacts_list()
    number = int(input("pick a number to remove: "))
    contacts.pop(number-1)
    print("contact deleted successfully")

# search for contact
def search():
    search = input("enter any number or name:")
    num = 0
    for contact in contacts:
        if search in contact.contact_name or search in contact.phone_number:
            num += 1
            print(f"{num}-)",end="")
            contact.show_contacts()
    if num == 0:
        print("contact not found")
        input("press enter")
        os.system("clear")
    else:
        input("press enter")
        os.system("clear")

contacts = []
while 1:
    menu = input("1.add new contact \n2.show contacts\n3.update contact\n4.remove contact\n5.search \n6.exit\n")
    os.system("clear")
    if menu == "1":
        add_contact()
        input("press enter ")
        os.system("clear")

    elif menu == "2":
        contacts_list()
        input("press enter ")
        os.system("clear")

    elif menu == "3":
        update_contact()
        input("press enter ")
        os.system("clear")

    elif menu == "4":
        delete_contact()
        input("press enter ")
        os.system("clear")

    elif menu == "5":
        search()

    else:
        break
import tkinter as tk
from tkinter import *
import os

#  تابع اضافه کردن مخاطب و ذخیره کردن
def add_contact():

    def add():
        name = en_contact.get()
        number = en_number.get()
        with open("phonebook.txt","a") as file1:
           file1.write(f"  {name} --> {number}  \n")
        win1.destroy()
    # پنجره اضافه کردن مخاطب
    win1 = tk.Tk()
    win1.title("add cantact")
    win1.geometry("230x150+610+230")

    lbl_contact = Label(win1,text="name: ")
    lbl_contact.grid(row=1,column=0)

    en_contact = Entry(win1,width=15,font=("Arail",14))
    en_contact.grid(row=1,column=1)

    lbl_number = Label(win1,text="number: ")
    lbl_number.grid(row=2,column=0)

    en_number = Entry(win1,width=15,font=("Arail",14))
    en_number.grid(row=2,column=1)

    btn_ad = Button(win1,text = "add and save",bd = 5,command=add)
    btn_ad.grid(row=3,column=0,columnspan=2,pady=10)

# تابع پنجره نمایش مخاطبین 
def show_contact():
    win2 = tk.Tk()
    win2.title("contacts")
    win2.geometry("230x150+610+230")

    scrol = Scrollbar(win2)
    scrol.pack(side=LEFT,fill=Y)
    with open("phonebook.txt","r") as file1:
           list1 = file1.readlines()
    mylist = Listbox(win2, yscrollcommand = scrol.set ,font=('Arail',12),width=30,height=10)
    for item in reversed(list1):
        mylist.insert(END,item)
    mylist.pack( side = LEFT,fill=BOTH)
    scrol.config(command=mylist.yview)

# جستجو کردن در لیست مخاطبین و حذف مخاطب   
def search_del_contact():

    with open("phonebook.txt","r") as file1:
        lst = file1.readlines()
    # تابع جستجو
    def search():

        s = entry_name.get()
        result_lbl.config(text=" ")
        for itm in lst:
            if s in itm :
                result_lbl.config(text=itm)
                break   
        else:
            result_lbl.config(text="Not found")
    # تابع حذف 
    def del_contact():
        d = entry_name.get()
        for itm in lst:
            if d in itm:
                lst.remove(itm)
                result_lbl.config(text = "this name delets.")
                with open("phonebook.txt",'w') as file2:
                   for item in lst:
                       file2.write(''.join(item))
                break
            else:
                result_lbl.config(text = "this name isn't in the phonebook.")
    #پنجره مربوط به دکمه جستجو
    win3 = tk.Tk()
    win3.title("search cantact")
    win3.geometry("230x150+610+230")

    lbl_name = Label(win3,text="name: ")
    lbl_name.grid(row=1,column=0)

    entry_name = Entry(win3,width=15,font=("Arail",14))
    entry_name.grid(row=1,column=1)

    btn_search2 = Button(win3,text = "search",command=search,font=("Arail",12))
    btn_search2.grid(row=2,column=0,columnspan=2)

    result_lbl = Label(win3,text = " ")
    result_lbl.grid(row=3,column=0,columnspan=2)

    btn_del = Button(win3,text = "del contacts",command=del_contact,font=("Arail",12))
    btn_del.grid(row=4,column=0,columnspan=2)
# پنجره اصلی
root = tk.Tk()
root.title("my phonebook")
root.geometry("250x150+600+100")

titr = Label(root,text = "My Contacts",bd = 5,font = ("b nazanin bold",14))
titr.grid(row=0 , column=0,columnspan=2)

# دکمه ها

btn_add = Button(root,text = "add contact",command=add_contact,font=("Arail",12))
btn_add.grid(row=2,column=0,padx=10,pady=10)

btn_show = Button(root,text = "show contacts",command=show_contact,font=("Arail",12))
btn_show.grid(row=2,column=1,padx=10,pady=10)

btn_search = Button(root,text = "search-del contact",command=search_del_contact,font=("Arail",12))
btn_search.grid(row=3,column=0,padx=10,pady=10,columnspan=2)

root.mainloop()

سلام
در این کد اضافه بر لیست مخاطب ها ،لیست مخاطبین حذف شده هم اضافه شده تا کاربر بتونه مخاطبینش رو حذف کنه و بعد اونارو ریکاوری کنه

contant_list = []
removed_list = []

class Contant:
    def __init__(self, name, number):
        self.name = name
        self.nunber = number
    def __str__(self):
        return f'{self.name}:{self.nunber}'

def show_list(x):
    print('--contacts list--')
    for j,i in enumerate(x): #برای شماره گذاری اعضای لیست و چاپ همراه با شماره
        print(f'{j+1}-{i}')

while True:
    x = input('1-enter new contant , 2-edit contants 3-remove contant 4-show contant list 5-recovery contact 0-exit : ')
    try:
        if x == '1':
            name = input('enter name: ')
            number = int(input('enter number: '))
            contant = Contant(name, number)
            contant_list.append(contant)
        if x == '2':
            if len(contant_list) > 0:
                show_list(contant_list)
                index = input('index of contant: ')
                name = input('enter new name: ')
                number = int(input('enter new number: '))
                contant = Contant(name, number)
                contant_list[int(index)-1] = contant
            else:
                print('!!there is not contant!!')
        if x == '3':
            if len(contant_list) > 0:
                show_list(contant_list)
                index = input('index of contant: ')
                removed = contant_list.pop(int(index)-1)
                removed_list.append(removed)
            else:
                print('!!there is not contant!!')
        if x == '4':
            if len(contant_list) > 0:
                show_list(contant_list)
            else:
                print('!!there is not contant!!')
        if x == '5':
            if len(removed_list) > 0:
                print('--removed contacts--')
                for i,j in enumerate(removed_list):
                    print(f'{i+1}-{j}')
                index = input('index of removed contant: ')
                recover = removed_list.pop(int(index)-1)
                contant_list.append(recover)
            else:
                print('!!there is not rmoved contant!!')
        if x == '0':
            break
    except ValueError:
        print('!!ValueError!!')
NAME=[]
NUMBER=[]
while True:
    X=input("1.add name&number    2.look      3.remove      4.edit : ")
    if X=="1":
        u=input("name :")
        n=input("number :")
        NAME.append(u)
        NUMBER.append(n)
    elif X=="2":
        print(NAME,"\n",NUMBER)
    elif X=="3":
        u=input("name :")
        n=input("number :")
        NAME.remove(u)
        NUMBER.remove(n)
    elif X=="4":
        print(NAME,"\n",NUMBER) 
        h=int(input("h:"))
        k=input("name :")
        l=input("number :") 
        NAME[h]=k
        NUMBER[h]=l
        print(NAME,"\n",NUMBER)
        break
contacts = {}  # دیکشنری برای ذخیره مخاطبان

def add_contact():
    name = input("نام مخاطب را وارد کنید: ")
    phone = input("شماره تلفن را وارد کنید: ")
    contacts[name] = phone
    print(f"مخاطب '{name}' با شماره '{phone}' اضافه شد.\n")

def view_contacts():
    if not contacts:
        print("دفترچه تلفن خالی است.\n")
        return
    print("لیست مخاطبان:")
    for name, phone in contacts.items():
        print(f"{name}: {phone}")
    print()

def search_contact():
    query = input("نام یا بخشی از نام مخاطب را وارد کنید: ")
    results = {name: phone for name, phone in contacts.items() if query.lower() in name.lower()}
    if results:
        print("نتایج جستجو:")
        for name, phone in results.items():
            print(f"{name}: {phone}")
    else:
        print("مخاطبی با این مشخصات یافت نشد.")
    print()

def edit_contact():
    name = input("نام مخاطبی که می‌خواهید ویرایش کنید را وارد کنید: ")
    if name in contacts:
        new_name = input("نام جدید را وارد کنید (یا Enter بزنید برای بدون تغییر): ")
        new_phone = input("شماره تلفن جدید را وارد کنید (یا Enter بزنید برای بدون تغییر): ")
        if new_name:
            contacts[new_name] = contacts.pop(name)
            name = new_name
        if new_phone:
            contacts[name] = new_phone
        print(f"اطلاعات مخاطب '{name}' به‌روزرسانی شد.\n")
    else:
        print("مخاطبی با این نام یافت نشد.\n")

def delete_contact():
    name = input("نام مخاطبی که می‌خواهید حذف کنید را وارد کنید: ")
    if name in contacts:
        del contacts[name]
        print(f"مخاطب '{name}' حذف شد.\n")
    else:
        print("مخاطبی با این نام یافت نشد.\n")

def main():
    while True:
        print("1. افزودن مخاطب جدید")
        print("2. مشاهده مخاطبان")
        print("3. جستجوی مخاطب")
        print("4. ویرایش مخاطب")
        print("5. حذف مخاطب")
        print("6. خروج")
        choice = input("یک گزینه انتخاب کنید: ")
        if choice == "1":
            add_contact()
        elif choice == "2":
            view_contacts()
        elif choice == "3":
            search_contact()
        elif choice == "4":
            edit_contact()
        elif choice == "5":
            delete_contact()
        elif choice == "6":
            print("خروج از برنامه.")
            break
        else:
            print("گزینه نامعتبر است. لطفاً دوباره تلاش کنید.\n")

# اجرای برنامه
if __name__ == "__main__":
    main()
contacts = {}


# Functions
def add_contact():
    # Adding Contacts
    b = input("Enter A Name: ")
    b1 = input("Enter A Number: ")
    if b1 in contacts.values():
        print("You Have A Contact With This Number!")
    else:
        contacts[b] = b1


def remove_contact():
    # Remove Contacts
    print(contacts)
    c = input("Enter A Name Or Number To Remove: ")
    for k, v in contacts.items():
        # Remove Contacts By Using Their Name
        if c == v:
            contacts.pop(k)
            break
        elif k == c:
            contacts.pop(c)
            break
        else:
            print("Invalid Number Or Name!")
        # Remove Contacts By Using Their Number


def show_contacts():
    # Show Contacts
    return contacts


def find_contacts():
    # Search In Contacts
    print(show_contacts())
    global d
    d = input("Enter A Name Or Number For Search: ")
    found = False
    for key, value in contacts.items():
        # Search in Cintacts By Using Their Number
        if value == d:
            print(f"This Number Belongs to {key}")
            found = True
            break
        # Search in Cintacts By Using Their Name
        elif key == d:
            print(f"The Number Of {key} is {value}")
            found = True
            break
    if found == False:
        # adding_none_exist_contact
        e = input("You Don't Have This Contact.Do You Want To Add It? Y/N\n")
        if e.lower() == "y":
            adding_none_exist_contact()
        elif e.lower() == "n":
            breakpoint
        else:
            print("Invalid Input!")


def adding_none_exist_contact():
    # adding_none_exist_contact
    if d.isdigit():
        d1 = input("Add A Name For This Contact: ")
        contacts[d1] = d
    else:
        d2 = input("Add A Number For This Contact: ")
        digit = False
        if d2.isdigit():
            digit = True
            contacts[d] = d2
        else:
            print("This Number Is Not Correct.")
            digit


def editing_contact():
    # Edit Contacts
    print(show_contacts())
    f = input("What Contact Or Number Do You Want To Change?\n")
    for ke, val in list(contacts.items()):
        # Edit Contacts By Using Their Name
        if ke == f:
            print(f"The Number Of {ke} Is {val}")
            f1 = input(
                "Do You Want To Change Name Or Number?(name For Name And num For Number.)\n"
            )
            if f1.lower() == "num":
                # Edit Number
                f1_1 = input("Enter A New Number: ")
                contacts[f] = f1_1
            elif f1.lower() == "name":
                # Edit Name
                f1_2 = input("Enter New Name: ")
                contacts[f1_2] = contacts.pop(f)
        # Edit Contacts By Using Their Number
        elif val == f:
            print(f"The Number Belongs To {ke}")
            f2 = input(
                "Do You Want To Change Number Or Name?(num For Number And name For Name.)\n"
            )
            if f2.lower() == "num":
                # Edit Number
                f2_1 = input("Enter New Number: ")
                contacts[ke] = f2_1
            elif f2.lower() == "name":
                # Edit Name
                f2_2 = input("Enter New Name: ")
                contacts[f2_2] = contacts.pop(ke)


def main():
    # Main App
    while 1:
        a = input(
            "Choose: 1.add a contact, 2.remove a contact, 3.show contacts, 4.search in contacts, 5.edinting contact, 0.end task\n"
        )
        if a == "1":
            # Add Contacts
            add_contact()
        if a == "2":
            # Remove Contacts
            remove_contact()
        if a == "3":
            # Show Contacts
            print(show_contacts())
        if a == "4":
            # Searching For Contacts
            find_contacts()
        if a == "5":
            editing_contact()
        # End Task
        if a == "0":
            break


# Start
main()

ارسال جواب

جوابت را با Markdown بنویس و ثبت کن

×
بستن