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

Show parent comments

2

u/shandelman Mar 01 '14

Though the first part of your explanation is spot on (minus the parentheses part which people have brought up), doesn't the foo function you propose obfuscate what the code is actually doing if anyone is going to read it after the fact? While and/or statements may be long because they require full boolean statements on either side, at least I know exactly what the code is doing, and don't have to cross-reference some other function to see what the programmer was going for.

1

u/xiongchiamiov xiongchiamiov Mar 01 '14

It'd be somewhat ok if the names were better.

2

u/shandelman Mar 01 '14 edited Mar 01 '14

I wonder if this would be a more "Pythonic" solution:

if any((string in xyz for string in strings)):

(Edited because I originally put "all" instead of "any" which would mimic an "and" instead of an "or")

1

u/[deleted] Mar 02 '14

Yep, I came to the same simplification. I vote this is most pythonic.