Python dictionary failsafe :python字典故障保护

Python dictionary failsafe

本问题已经有最佳答案,请猛点这里访问。

我已经用python创建了一个字典作为我的第一个"专业"项目。我用它来跟踪关键词。输入的只是示例,请随时改进我的定义(:

我对python不太熟悉,所以请随意批评我的技术,这样我就可以在它变得更糟之前学会它了!

我想知道的是,是否有一种方法可以处理字典中未包含的搜索。

如"抱歉,找不到您要查找的单词,是否要尝试其他搜索?"

不管怎样,我的代码是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
Running = True

Guide = {
'PRINT': 'The function of the keyword print is to: Display the text / value of an object',

'MODULO': 'The function of Modulo is to divide by the given number and present the remainder.'
'
 The Modulo function uses the % symbol'
,

'DICTIONARY': 'The function of a Dictionary is to store a Key and its value'
'
 separated by a colon, within the {} brackets.'

'
 each item must be separated with a comma'
,

'FOR LOOP': 'The For Loop uses the format:
 '

            'For (variable) in (list_name): (Do this)',

'LINE BREAKS': ' \ n ',

'LOWERCASE': 'To put a string in lower case, use the keyword lower()',

'UPPERCASE': 'To put a string in upper case use the keyword upper()',

'ADD TO A LIST': 'To add items to a list, use the keyword: .append'
'
 in the format: list_name.append(item)'
,

'LENGTH': 'To get the length of a STRING, or list use the keyword len() in the format: len(string name)', }

while Running:
    Lookup = raw_input('What would you like to look up? Enter here: ')
    Lookup = Lookup.upper()
    print Guide[str(Lookup)]
    again = raw_input('Would you like to make another search? ')
    again = again.upper()
    if again != ('YES' or 'Y'):
        Running = False
    else:
        Running = True


您可以使用try/except块:

1
2
3
4
5
6
7
try:
    # Notice that I got rid of str(Lookup)
    # raw_input always returns a string
    print Guide[Lookup]
# KeyErrors are generated when you try to access a key in a dict that doesn't exist
except KeyError:
    print 'Key not found.'

此外,为了使代码正常工作,您需要使这一行代码:

1
if again != ('YES' or 'Y'):

这样地:

1
if again not in ('YES', 'Y'):

这是因为,正如目前的情况,您的代码正被类似于python的代码评估:

1
if (again != 'YES') or 'Y':

此外,由于非空字符串在python中对True进行计算,因此这样的代码将使if语句始终返回True,因为'Y'是非空字符串。

最后,您可以完全摆脱这一部分:

1
2
else:
    Running = True

因为它只为已经等于的变量赋值。


两种选择。

使用in运算符:

1
2
3
4
5
6
7
8
9
d = {}

d['foo'] = 'bar'

'foo' in d
Out[66]: True

'baz' in d
Out[67]: False

或者使用字典的get方法,并提供参数的可选默认值。

1
2
3
4
5
d.get('foo','OMG AN ERROR')
Out[68]: 'bar'

d.get('baz','OMG AN ERROR')
Out[69]: 'OMG AN ERROR'


如果你更换,你可以得到你想要的

1
print Guide[str(Lookup)]

具有

1
2
badword = 'Sorry, the word you were looking for could not be found, would you like to try another search?'
print Guide.get(lookup,badword)

有一件事跳了出来,就是用大写字母给你的听写命名。一般来说,大写字母是为班级保留的。另一个有趣的事情是,这是我第一次看到一个实际上用作字典的听写。:)