Program with boolean expressions enters the if block every time

Asked

Viewed 69 times

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 don’t understand why or when used returns everything as True instead of selecting the variables I typed in the code.

2 answers

3


The or does not work as you imagine, the correct would be:

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

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

You were comparing the expression letter[0] == "Q" which may be true or false according to the value of letter[0]. How do you have a 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 so far so good. 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 zeroed or empty are false, all other values are true, so "O" is true. So every time the first expression gives false and he will try the second this is always true, and therefore makes everything be true.

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

The other changes I made because it’s more readable and obvious

  • Thank you for clearing my doubt.

3

Another way of doing it would be:

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

See working on Repl.it | Ideone | Github GIST

Basically replacing the two comparisons with == by the operator in and verification by a condition inline, or ternary, if you prefer. I particularly find this form more readable for humans.

  • I had never seen before the use of operators within a line, thanks for the tip I’ll give a search on this also.

  • Is there any special reason (maybe performance) to use set instead of lista/tuple in this case?

  • 1

    @Miguel yes, the search in a set is O(1), while in others it is O(n), but not necessarily this is reflected in the execution, given the size of the set.

  • Thank you Anderson, yes, that’s reason enough.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.