简体   繁体   中英

Why won't my True statement work?

Here is a dictionary:

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

I've created a simple set of if statements in a loop:

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': ")

For some strange reason, when the user inputs a key that is in the dictionary, the code outputs:

"That's not a word"

Why isn't the if statement with the '== True' working?

You don't need to use if t1 in Vocab == True , simply use if t1 in Vocab .

The problem is the operand precedence. The == has priority over in , so when you write if t1 in Vocab == True python interprets as if t1 in (Vocab == True) .

To fix the precedence issue, you can write like this: if (t1 in Vocab) == True: , but again there is no need to compare if the result of t1 in Vocab is True , simple use this:

if t1 in Vocab:

You shouldn't need to use the "== True." Python should evaluate the if statement when you use this syntax without that.

A couple of things. First, if you're on Windows, there is the possibility that it might not be stripping the '\\r' at the end of the input line, or you might have extra whitespace in general from your input. But also, you can simplify your code significantly, as so:

    t1=raw_input("What word matches this definition?: ")
    try:
        if Vocab[t1.strip()] == x:  # This should fix your 'not a word' problem
            print "That's Correct"!
        else:
            print "That's Wrong!"!
    except KeyError:
        print "That's not a word!"

There's no need to test if a key is in a dictionary before using it. Simply try and use it and then catch the resulting KeyError .

edit

@MagnunLeno is also totally correct about the precedence problem, although simplifying your code as I have recommended makes it a moot point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM