Python - 交互式电话簿

时间:2016-10-13 10:45:45

标签: python split interactive

我需要帮助,在raw_input一行的字典中添加姓名和电话号码。它应该如下所示:add John 123(将名称John添加到数字123)。这是我的代码:

def phonebook():
    pb={}
    while True:
        val,q,w=raw_input().split(" ")
        if val=='add':
            if q in pb:
                print
                print "This name already exists"
                print
            else:
                pb[q]=w #lägger till namn + nummer i dictionary
        if val=='lookup':
            if q in pb:
                print
                print pb[q]
                print
            else:
                print "Name is not in phonebook"
                print 

我收到解包错误。有小费吗?还有其他办法吗?

2 个答案:

答案 0 :(得分:2)

以下一行假定您输入3个单词,每个单词用空格字符分隔:

val, q, w = raw_input().split(" ")

如果你有少于或多于3个单词(使用查找命令就是这种情况,不是吗?),你将收到解包错误。

您可以在唯一变量中获取输入,然后测试其第一个元素以避免错误:

in_ = raw_input().split(" ")
if in_[0] == 'add':
    # process add action
if in_[0] == 'lookup':
    # process lookup action

奖励提示:您不需要将空格字符赋予split方法,因为它是默认值:

raw_input().split()  # will work as well

答案 1 :(得分:1)

我认为当您使用"查找john"查找某人时会收到解包错误。代码在分割中查找第三个值("")但找不到。

我不确定这是否有帮助:

def phonebook():
pb={}
while True:
    vals = raw_input().split(" ")
    if vals[0] == 'add':
        q = vals[1]
        w = vals[2]
        if q in pb:
            print "This name already exists"
        else:
            pb[q]=w #lägger till namn + nummer i dictionary
    elif vals[0]=='lookup':
        q = vals[1]
        if q in pb:
            print
            print str(q) + "'s number is: " + str(pb[q])
            print
        else:
            print "Name is not in phonebook"
            print

回复我:

>add j 12
>add j 12
This name already exists
>lookup j

j's number is: 12

>lookup j 12

j's number is: 12

>lookup k
Name is not in phonebook
相关问题