-1

this is my code:

for count in range(NOI):
        ig=input("enter a GTIN code: ")
        while ig!=("21356797"):
                print("incorrect")
                ig=input("enter a GTIN code: ")
                count =count+1

and this is the output:

21356797

13246785

31325974

45689413

34512340

56756777

how many items do you want to buy?: 1
enter a GTIN code: 21356797
>>> 

which is what i want. However once i put in OR in my while loop, i can't get it to work like the first part:

while ig!=("21356797" or "13246785"):
            print("incorrect")
            ig=input("enter a GTIN code: ")
            count =count+1 

and this is the output:

how many items do you want to buy?: 1
enter a GTIN code: 13246785
incorrect
enter a GTIN code: 21356797
>>> 
  • Maybe `while ig!=("21356797" or "13246785"):` => `while not ig in ["21356797", "13246785"]:` Using `or` between 2 strings doesn't really make sense since strings are not Boolean values (although they can be coerced to such, which isn't really what you want). – John Coleman Dec 31 '16 at 17:25
  • 1
    `"21356797" or "13246785"` is "21356797", look up the or operator in python. You have to do `ig != ... or ig != ...` – Jasper Dec 31 '16 at 17:27
  • @Jasper: You need to `and` the conditions together, not `or` them, if you're using `!=`. Otherwise, nothing ever passes, since it will be unequal to one of the values all the time. – ShadowRanger Dec 31 '16 at 17:31
  • Possible duplicate of [How do I test one variable against multiple values?](http://stackoverflow.com/questions/15112125/how-do-i-test-one-variable-against-multiple-values) – DeepSpace Dec 31 '16 at 17:35

1 Answers1

2

Your test:

ig!=("21356797" or "13246785")

evaluates the or condition first, returning the first "truthy" value. As such, it's exactly equivalent to:

ig!= "21356797"

since "21356797" is truthy.

You want a containment test:

ig not in ("21356797", "13246785")

or two sequential != tests and-ed together:

ig != "21356797" and ig != "13246785"
# Equivalent to:
not (ig == "21356797" or ig == "13246785")

The containment test scales to a larger set of values more cleanly, and as long as all the values are string literals, will be equally efficient (CPython caches the constant tuple of literals).

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271