Atom Roese Atom Roese - 2 months ago 7
Python Question

python always returns if statement as true if i use or

I'm relatively new to programming, and while i was making a simple scanner that runs a command whenever it finds a forward-slash (/) or a back-slash (\), it outputs things that (i think) it shouldn't be outputting.

here is the code:

loop = 0
a = 'm/es\s/a/ge'
while loop <= len(a)-1:
if a[loop] == '/' or '\\':
print ('found at: ' + str(loop))
loop += 1


This outputs:

found at: 0
found at: 1
found at: 2
found at: 3
found at: 4
found at: 5
found at: 6
found at: 7
found at: 8
found at: 9
found at: 10


when it should only print anything 4 times (as there is only 4 slashes in the string)

I tried removing "or" along with the other possible value, and it did what it should, so the problem must be with the "or"

am I using "or" wrong? or is this something else?

EDIT:
I tried How do I test one variable against multiple values?, but that question is asking how to test multiple variables against a single value, while I need to know how to test a single variable against multiple possible values

Answer

You want to use

if a[loop] == '/' or a[loop] == '\\'

else the '\\' will always return true.

Comments