Program with boolean expressions enters the if block every time

0
    prefixes = "JKLMNOPQ"
    suffix = "ack"
    for letter in prefixes:
        if letter[0] == "Q"or"O":
            print(letter+"uack")
            continue
        print(letter+suffix)

Expected response:

Jack
Kack
Lack
Mack
Nack
Ouack
Pack
Quack

Response Acquired:

Juack
Kuack
Luack
Muack
Nuack
Ouack
Puack
Quack

I do not understand why or when used returns everything as True ao instead of selecting variables that I typed in code.

    
asked by anonymous 06.06.2018 / 22:22

2 answers

3

or does not work as you think, the correct one would be:

prefixes = "JKLMNOPQ"
for letter in prefixes:
    if letter[0] == "Q" or letter[0] == "O":
        print(letter + "uack")
    else:
        print(letter + "ack")

You were comparing the expression letter[0] == "Q" which can be true or false according to the value of letter[0] . Since it has or , the only way the decision can be made without evaluating anything else is when this expression is true, because it is certain that the block must be executed. And that's right. The or is also appropriate there. The problem is in the second expression of or that does not return what you expect.

What is the Boolean result of "O" ? By definition, all values that are not considered zero or empty are false, all other values are true, so "O" is true. So every time the first expression gives false and it will try the second it is always true, and therefore makes everything true.

What you actually wanted to do is letter[0] == "O" because the expression might be true at the right time, but will give false in most cases.

The other changes I made because it is more readable and obvious

    
06.06.2018 / 22:35
3

Another way to do it would be:

prefixes = 'JKLMNOPQ'
for prefix in prefixes:
    suffix = 'uack' if prefix in {'Q', 'O'} else 'ack'
    print(prefix + suffix)

See working at Repl.it | Ideone | GitHub GIST

Basically by replacing the two comparisons with == with the in operator and checking with an inline condition, or ternary, if you prefer. I particularly find this form more human readable.

    
06.06.2018 / 22:46