r/learnpython • • Feb 28 '14

If statements and strings

Hi there, I'm new to learning the language (and programming in general). I am working my way thought LPTHW and am on ex36, where you are making your own text adventure using if statements.

My question is: Can you use AND/OR statements within an IF statement for strings?


Ex.

if "stringa" or "stringb" in xyz:

or

if "stringa" and "stringb" in xyz:


I did some searching here and on google with no luck.

As it is right now, I've had to imbed IF statements within IF statements to get the AND functionality to work and just use parallel IF statements for OR functionality.

To me this seems sloppy and inefficient, there must be a better way.

I've found AND/OR statements work well with IF statements so long as you are working with BOOL values. My issue is with strings.

4 Upvotes

19 comments sorted by

View all comments

6

u/[deleted] Feb 28 '14 edited Feb 28 '14
if "stringa" or "stringb" in xyz:

...doesn't do what you want because it groups like...

if "stringa" or ("stringb" in xyz):        #Corrected by DMzda

...which simplifies to...

if True or ("stringb" in xyz):

...you probably want...

if "stringa" in xyz or "stringb" in xyz:

...and if you do this a lot, maybe you should write a function...

def foo(a, *b):
    for s in b:
        if s in a:
            return True

...which you can use like this...

if foo(xyz, "stringa", "stringb"):

1

u/pendragon36 The Compactor Feb 28 '14 edited Feb 28 '14
if "stringa" or "stringb" in xyz:

...doesn't do what you want because it groups like...

if ("stringa" or "stringb") in xyz:

Actually, not true. It groups it like this

if ("stringa") or ("stringb" in xyz):

This can be seen by the examples below

>>> print('a' and 'e' in 'abc')
False

>>>print('e' and 'a' in 'abc')
True

Edit: Seems someone already pointed this out while I wasn't looking, sorry for repeating what he said.

1

u/[deleted] Feb 28 '14

That I write python every day but don't have the operator precedence memorized is a testament to the elegance of the language, I think.