Skip to main content
 首页 » 编程设计

python之为什么我的 True 陈述不起作用

2025年05月04日14freeliver54

这是一本字典:

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"} 

我在循环中创建了一组简单的 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': ") 

由于某些奇怪的原因,当用户输入字典中的键时,代码输出:

"That's not a word" 

为什么带有“== 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: