我正在尝试做我的 Python 作业,但我的代码无法正常工作

问题描述 投票:0回答:0

嗨,我正在尝试为我的家庭作业制作电话簿,我必须使用 try 和 except 块来处理错误我认为我的 try 和 except 块很好,但代码运行不正确。这是代码(不要介意它们是给我老师的评论块):`dictionary = {} #I add a dictionary to store all the users and phonenumbers class InvalidPhoneNumberError(Exception): #我没有使用这个异常类 通过

班级电话簿:

def __init__(self,name=None,phone_number=None): #I defined needed informations for this program
    self.name = name
    self.phone_number = phone_number

def add_contact(self,name,phone_number):   #its the add contact function to add new contact to dictionary I used try and except blocks
    try:
        dictionary.update({name:int(phone_number)})
    except ValueError:
        print("This numebr is not correct")


def search_contact(self,name):    #its the search contact function to search if there is a contact that given name in the dictionary I used try and except block
    try:
        if name in dictionary:
            print("Contact name :",name)
            print("Contact phone number:",dictionary.get(name))
        else:      #I don't know why my if I don't use else and raise KeyError in here code don't work. it don't give error it just dont work at all but I think I used try and except correct and my check system is also correct
            raise KeyError

    except KeyError:
        print("There is no user in this name")

def modify_contact(self,name): #its the modify conect function to modify phone number that given name. I used try and except blocks but it dont work with try and except blocks
    try:
        if name == dictionary[name]:
            x = input("Change the number: ")
            dictionary.update({name:x})
        else: #for example like seach_contact function it needs a else in here but even if I put else here it don't work correctly if I put else and KeyError it always raise KeyError if I don't but else code just don't work at all
            pass

    except KeyError:
        print("There is no user in this name")

if name == "main": 电话簿 = 电话簿()

while True:
    print("1. Add contact")
    print("2. Search contact")
    print("3. Modify contact")
    print("4. Exit")
    choice = input("Enter your choice: ")

    if choice == "1":
        name = input("Enter name: ")
        phone_number = input("Enter phone number: ")

        phonebook.add_contact(name, phone_number)

    elif choice == "2":
        name = input("Enter name: ")
        phonebook.search_contact(name)

    elif choice == "3":
        name = input("Enter name: ")
        phonebook.modify_contact(name)

    elif choice == "4":
        break

    else:
        print("Invalid choice")

`

我尝试用不同的方式编写代码,但没有成功

python error-handling try-except
© www.soinside.com 2019 - 2024. All rights reserved.