r/learnpython • u/live4hisglory • 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.
1
u/Yoghurt42 Mar 01 '14
An alternative way to get what you want is using "any":
if any(needle in xyz for needle in ("stringa", "stringb")):-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
1
0
u/live4hisglory Feb 28 '14
Ok, I didn't think of testing it simply like that, it must be an issue elsewhere in my code.
6
u/[deleted] Feb 28 '14 edited Feb 28 '14
...doesn't do what you want because it groups like...
...which simplifies to...
...you probably want...
...and if you do this a lot, maybe you should write a function...
...which you can use like this...