2016-10-05 3 views
1

Ich versuche, ein Projekt von Telefon Menü zu machen, mit dem Anzeigen, Hinzufügen und Entfernen von Kontakten. Welcher Weg wäre besser, Kontakt zum Wörterbuch hinzuzufügen oder neue Dateien zu erstellen und daraus zu lesen/lesen?Telefon Menü - Python 3

Ich versuchte erste Methode - Ich hatte neuen Kontakt zu leeren Wörterbuch hinzugefügt und dann habe ich versucht, es anzuzeigen, indem Sie die Option anzeigen, aber immer noch Wörterbuch ist leer.

, dass eine erste Probe von meinem „Projekt“ ist:

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") 
     x[new_key] = new_value 
     print(phone_contacts) 


    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 

dies nicht auf diese Weise nicht funktioniert, habe ich auch versucht

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 

Es tut in eine Datei schreiben text.txt arbeite auch nicht.

Was mache ich in beiden Fällen falsch? Welchen Weg soll ich wählen, erster oder zweiter?

BTW Ich wäre dankbar für irgendwelche Tipps, wie ich meinen Code korrigieren könnte, auch wenn diese Tipps nicht zu dem Problem gehören.

Antwort

0

In beiden Optionen überschreiben Sie das Wörterbuch bei jeder Iteration. Sie sollten es nur einmal außerhalb der Schleife initialisieren. Für die erste Option sieht es so aus:

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 

    # ... 
0

Sie sollten alle Funktionen vor und außerhalb der Hauptsache while (True) definieren. Sie sollten den ifs-Block in eine Funktion umwandeln, die die Eingabe empfängt. Sie sollten explizit angeben, welcher Schlüssel welche Option ist.

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:')) 
0

Als erstes müssen Sie phone_contacts und die Funktionen außerhalb der Schleife deklarieren.

Zweitens gibt es Redundanzen in den Bedingungen.

Die Idee, eine Datei zum Speichern von Kontakten zu erstellen, ist großartig. Ich würde es als .json Datei speichern, da es sehr einfach zu handhaben ist.

Hier ist der Code, den ich so gut wie möglich refaktoriert habe.

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() 

Beachten Sie auch, dass Sie nicht brauchen, um phone_contacts als Argument übergeben, da es global ist.

Ich habe Laden und Speichern von Kontakten Funktionen hinzugefügt, die ziemlich verständlich ist, auch wenn Sie keine Erfahrung mit JSON haben.

Es gibt eine Menge Dinge zu fragen, also wenn Sie Zweifel haben und mich fragen wollen, fühlen Sie sich wohl! ;)

+0

Danke für Ihre Mühe, mir zu helfen! Können Sie mir sagen, warum Sie diese "try/except" -Methode im Code verwendet haben? Ich habe versucht, etwas darüber zu finden, aber ich verstehe es nicht. Wann sollte ich es benutzen und wozu dient es? –

+0

try/except wird für die Behandlung von Fehlern in Ihrem Programm verwendet. Sie sollten es immer dann verwenden, wenn Ihr Programm etwas auf unerwartete Weise ausführt, um zu verhindern, dass diese Ausnahme Ihre Anwendung zum Absturz bringt. In diesem Fall habe ich beispielsweise try/except verwendet, um den Inhalt zu lesen, der möglicherweise nicht in einer Datei existiert, die möglicherweise nicht existiert. Wenn die Ausnahme ausgelöst wird, wird der Code einfach ein leeres Wörterbuch erstellen. Versuchen Sie, die try/except-Anweisung zu entfernen, und führen Sie den Code mit und ohne die Datei contacts.json im Verzeichnis aus.Auch [um Vergebung bitten] (https://docs.python.org/3.4/glossary.html#term-eafp) –