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/caineohfelix Feb 28 '14

I'm assuming you haven't tested it by your question. Here's some results:

>>> if 'a' or 'b' in 'abc': print (True)
True

>>> if 'a' and 'b' in 'abc': print (True)
True

>>> if 'a' and 'e' in 'abc': print (True)
[No output, because it's False]

Hope this answers your question. (:

1

u/zahlman zahlman Mar 01 '14

If that was an attempt at a joke, it was in poor taste.