Python - 从字典列表中检索信息&语法错误

时间:2012-05-04 15:26:55

标签: python dictionary

我正在尝试使用Python找出一个“简单”的字典/数据库,它将从十个列表中检索一个名称,并提供所请求的信息。 即输入是'John phone';输出是'约翰的电话号码是0401'。

除了完全停留在特定信息的检索上之外,python突然在name = raw_input行上给我一个语法错误。

以下是我保存为“朋友”的文件:

#!/usr/bin/python

friends = {'John' : {'phone' : '0401',
        'birthday' : '31 July',
        'address' : 'UK',
        'interests' : ['a', 'b', 'c']},
    'Harry' : {'phone' : '0402',
        'birthday' : '2 August',
        'address' : 'Hungary',
        'interests' : ['d', 'e', 'f']}}
name = raw_input ('Who are you looking for? ')
if name in friends: 
print friends[name]"'s phone number is: "['phone']
    # this line is something I haven't tested
    # and so I have a big hunch it's not going to work
else: 
    print 'no data'

这是它给我的错误:

$ ./friends
File "./friends", line 11
name = raw_input ('Who are you looking for? ')
     ^
SyntaxError: invalid syntax

请注意,几个小时前,当我使用imac上的终端处理同一个文件时,这是。我没有改变那条线,我完全不知道为什么它在播放!

  • 也不适用于我的电脑上的cygwin或其他借来的mac。
  • 是的,我已经将chmod + x好友输入了终端。

这可能是最简单,最愚蠢的事情,而且我可能完全忽略了某些事情或意外碰到了一把钥匙(它是凌晨1点......这是周一到期的......),但是任何帮助都会非常感激!

2 个答案:

答案 0 :(得分:2)

raw_input()行可以正常使用。

“不确定”行有语法错误。它可以这样读:

print name + "'s phone number is: " + friends[name]['phone']

您还可以使用格式字符串:

print "%s's phone number is: %s" % (name, friends[name]['phone'])

完整if阻止:

if name in friends: 
    print "%s's phone number is: %s" % (name, friends[name]['phone'])
else: 
    print 'no data'

否则,直接从您的帖子复制/粘贴后,您的代码对我有效。

答案 1 :(得分:1)

您在打印邮件的行中有语法错误,忘记缩进(在python中这不是可选的。)。

以下是一些固定版本:

print name + "'s phone number is: " + friends[name]['phone']
print "%s's phone number is: %s" % (name, friends[name]['phone'])

其他行非常精细,所以你得到的错误很奇怪。

相关问题