use*_*442 1 python dictionary if-statement
这是一本字典:
Vocab ={'Adherent' : " supporter; follower.",
'Incoherent' : "without logical or meaningful connection; disjointed; rambling",
'Inherent' : "existing in someone or something as a permanent and inseparable element, quality, or attribute"}
Run Code Online (Sandbox Code Playgroud)
我在循环中创建了一组简单的if语句:
while 1:
x = Vocab[random.choice(Vocab.keys())]
print x
t1=raw_input("What word matches this definition?: ")
if t1 in Vocab == True:
if Vocab[t1] == x:
print "That's correct!"
elif Vocab[t1] != x:
print "That's wrong!"
else:
print "That's not a word!"
raw_input("Hit 'enter': ")
Run Code Online (Sandbox Code Playgroud)
出于某些奇怪的原因,当用户输入字典中的键时,代码输出:
"That's not a word"
Run Code Online (Sandbox Code Playgroud)
为什么'== True'的if语句不起作用?
您不需要使用if t1 in Vocab == True,只需使用if t1 in Vocab.
问题是操作数优先级.在==超过了优先级in,所以当你写if t1 in Vocab == True的Python解释为if t1 in (Vocab == True).
要解决优先级问题,可以这样编写:if (t1 in Vocab) == True:,但是再次没有必要比较结果t1 in Vocab是否True,简单使用:
if t1 in Vocab:
Run Code Online (Sandbox Code Playgroud)