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

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)