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

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"):

2

u/DMzda 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:

...which simplifies to...

if True in xyz:

It actually groups like this:

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

which always evaluates to True as "stringa" is True.

1

u/live4hisglory Feb 28 '14

right, this is the issue I was having. Any solutions on getting around this?

1

u/live4hisglory Feb 28 '14

nevermind, I see sailboats answer was correct, just the explanation needed some help.

1

u/[deleted] Feb 28 '14

Oh, good catch.

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.

1

u/[deleted] Mar 01 '14

Yeah that foo function is downright terrible, but in principle, a well-named clearly-written test function has its place...

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.

1

u/ingolemo Mar 01 '14

The way that the expression is grouped together isn't actually that important because neither "stringa" or ("stringb" in xyz) nor ("stringa" or "stringb") in xyz would do what the op wants. The real problem is that python has no way to know that the op wants it to distribute the in xyz operation over the or operator.

1

u/autowikibot Mar 01 '14

Distributivity:


In abstract algebra and logic, the distributive property of binary operations generalizes the distributive law from elementary algebra. In propositional logic, distribution refers to two valid rules of replacement. The rules allow one to reformulate conjunctions and disjunctions within logical proofs.

For example, in arithmetic:

In the left-hand side of the first equation, the 2 multiplies the sum of 1 and 3; on the right-hand side, it multiplies the 1 and the 3 individually, with the products added afterwards. Because these give the same final answer (8), we say that multiplication by 2 distributes over addition of 1 and 3. Since we could have put any real numbers in place of 2, 1, and 3 above, and still have obtained a true equation, we say that multiplication of real numbers distributes over addition of real numbers.


Interesting: Distributive ^property | Distributivity (order ^theory) | Principle of ^distributivity | Completely distributive ^lattice | Lattice ^(order)

Parent commenter can toggle ^NSFW or ^delete. Will also delete on comment score of -1 or less. | FAQs | ^Mods | Magic ^Words | [flag a glitch](http://www.reddit.com/message/compose?to=/r/autowikibot&subject=Glitched comment report&message=What seems wrong: (optional description goes here)%0A%0A---%0A%0AReply no. 75218:%0Ahttp://www.reddit.com/r/learnpython/comments/1z7j2u/if_statements_and_strings/cfrk00h)

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

u/zahlman zahlman Mar 01 '14

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

1

u/xiongchiamiov xiongchiamiov Mar 01 '14

It answers it, just incorrectly.

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.