-1

This has confused me for a long time. I can't understand why if "str" or "str2" in i: is so glitchy. You don't even have to have either of those inputs for it to run the code in the if.

I'm asking if there is any way to get around this, and (optional) I would like to see why this happens.

Below is example script 1

i = input(">>> ")
if ";" in i:
    print("Command")
else: 
    print("Nope")


>>> ;
Command
>>> da
Nope

Now for the buggy part I can't explain

i = input(">>> ")
if ";" or ":" in i:
    print("Command")

>>> ;hello
Command
>>> anything
Command
>>> this doesn't have semicolon or colon, yet still says command.
Command

My IDE is IDLE, (most recent version) which creates the same output as the terminal running...

GuyOnDR0G
  • 11
  • 3
  • I am guessing it should be `if ';' in i or ':' in i:`. – samkart Dec 28 '18 at 08:27
  • Possible duplicate of [How to test multiple variables against a value?](https://stackoverflow.com/questions/15112125/how-to-test-multiple-variables-against-a-value) – guidot Dec 28 '18 at 09:36

2 Answers2

1

No it is not a Python glitch.

See:

i = "anything"
if (";" in i) or (":" in i):
    print("Command")
else:
    print("No command")

vs.

i = "anything"
if ";" or ":" in i:
    print("Command")
else:
    print("No command")

The first code sample works while the second does not. The reason: Python will evaluate strings (as any other value) as booleans if you specify ";" or ":" in i. Therefor your expression evaluates to True which is - I guess - not what you intended :-)

Regis May
  • 3,070
  • 2
  • 30
  • 51
0

I try a generic answer: This is a frequent misunderstanding (quite independent from the programming language; some may flag it as syntax error however).

or is much more specific than the English or. It simply combines two truth values.

str in i

is one truth value, so someone has to decide how to treat str2,. Python decides it is true if the string is non-empty, other programming languages could report an error since instead of a truth value a string is found. Your intended behavior, that str2 is also (automatically) compared to i, is plausible in English but has to be stated explicitly in any programming language I know of.

guidot
  • 5,095
  • 2
  • 25
  • 37