另一个问题:电话字典问题“whileloop”使用错误

2024-10-01 13:24:15 发布

您现在位置:Python中文网/ 问答频道 /正文

简单问答电话词典

我想做的是把人的名字和号码放在字典里查找

我想做什么

Enter command (a, f, d, or q).: a

Enter new name................: Perry

Enter new phone number........: 229-449-9683


Enter command (a, f, d, or q).: f

Enter name to look up...: 

我想在键入时查找全名和号码

电话字典代码我到目前为止写的:


phone_dict = {}
command = input('Enter command (a, f, d, or q).: ')
newname = input('Enter new name................: ')
newphone = input('Enter new phone number........: ')
while True:
    if command == 'a':
        newname
        newphone
        phone_dict[newname] = newphone
        print(phone_dict)
# In here, 'while-loop' does not work. 

在这里,如果我输入'a'命令并键入名称

这本字典应该是{Perry:229-449-9683}

谢谢,这个问题可能有点困惑,但如果你能帮我解决这个问题,我很高兴


Tags: ornamenumbernewinput字典phonedict
2条回答

要使用此人的姓或名查找号码,您可以执行以下操作:

a = 'Add a new phone number'
d = 'Delete a phone number'
f = 'Find a phone number'
q = 'Quit'
phone_dict = {}

while True:
    # Gets the user command every loop
    command = input('Enter command (a, f, d, or q).: ')

    # Add a new registry to the directory
    if command == 'a':
        newname = input('Enter new name................: ')
        newphone = input('Enter new phone number........: ')
        phone_dict[newname] = newphone
        print(phone_dict)

    # Find a registry on the directory
    elif command == "f"
        query = input("Enter name to look up...: ")
        match = None
        for key in phone_dict.keys():
            if query.strip() in key:
                match = phone_dict[key]
                break
        if match is None:
            print(f"The name {query} could not be found on the directory")
        else:
            print(f"The phone number of {query} is {match}")
    elif command == "d":
        # Delete registry
    elif command == "q":
        # Quits program
    else:
        print(f"The command {command} was not found, please try again!")

在本例中,我使用query.strip()删除任何可能导致找不到此人的额外开始/结束空格

请让我知道这是否有帮助。谢谢

要从字典中查找结果,您可以循环遍历这些项并检查键是否包含要查找的字符串。如果要获取满足查询的所有值,可以创建另一个列表或字典并存储找到的项:

phone_dict = {
    "Han Perry": "1234",
    "Harry Gildong": "2345",
    "Hanny Test": "123",
}


find_str = "Han"

result = {}

for key, value in phone_dict.items():
    # Converting it to lower makes it case insensitive
    if find_str.lower().strip() in key.lower():
        result[key] = value

print(result)
# {'Han Perry': '1234', 'Hanny Test': '123'}

请注意,这将贯穿字典的所有值:O(n)

相关问题 更多 >