python在使用raw_input时有条件(Newbie)

时间:2012-09-28 03:12:47

标签: python python-2.7 conditional raw-input

我对使用in conditionalraw_input.

有疑问

基本上我试图用Python搜索字典并评估用户输入。我试图检查用户输入是否在字典中。

(我不会包括字典)

shortname=raw_input('Please enter a short name that corresponds to the dictionary: ')

if shortname in paperwork:
    print paperwork['shortname']

else:
    print 'Name Not Found'

问题是当我评估用户输入时,它实际上是真的时将其声明为false。有人能告诉我我做错了什么来帮助我吗?

文书工作中的“短名称” 假

(当我手动检查它是否有效时,我得到了什么)

我环顾四周,我认为这个问题是如此基本,而不是在这里。谢谢!

1 个答案:

答案 0 :(得分:0)

除了你的错误

if shortname in paperwork:
    print paperwork['shortname']

您使用的是字符串文字shortname

,而不是使用变量'shortname'

我在这个例子中没有遇到任何问题:

lettersStored = ['a','b','c','d']
name=raw_input('Please enter a letter:\n')

if name in lettersStored:
    print "Found it at index %d " % (lettersStored.index(name))
else:
    print 'Not found'

我用输入测试了它:

a  (Found it at index 0)
b  (Found it at index 1)
c  (Found it at index 2)
z  (Not Found) 
x  (Not Found)