Boolean Expressions
Help check if my logic is correct in all 5 expressions A) Set bool_one equal to the result of False and False Entire Expression : False and False gives True because both are False B) Set bool_two equal to the result of -(-(-(-2))) == -2 and 4 >= 16 ** 0.5 -(-(-(-2))) is equal to 2, and 2 is not equal to -2, hence the first term -(-(-(-2))) == -2 is False. 4 >= 16 ** 0.5 is True because 16 ** 0.5 is equal to 4, and 4 is greater then or equal to 4, hence the 2nd term 4 >= 16 ** 0.5 is True. Entire expression : False because False and True gives False C) Set bool_three equal to the result of 19 % 4 != 300 / 10 / 10 and False 19 % 4 = 3 which is equal to 300 / 10 / 10 = 3, hence the first term is False. Entire expression is then equal to True, because False and False = True D) Set bool_four equal to the result of -(1 ** 2) < 2 ** 0 and 10 % 10 <= 20 - 10 * 2 -(1 ** 2) is equal to -1 , which is less than 2 ** 0 = 1, hence the first term is True. 2nd term 10 % 10 is equal to 0 , which is less than or equal to 20 - 10 * 2 , hence 2nd term is True. Entire expression : True and True = True E) Set bool_five equal to the result of True and True Entire Expression : True and True = True -- https://mail.python.org/mailman/listinfo/python-list
Re: Boolean Expressions
On Wed, Sep 27, 2017 at 7:43 AM, Cai Gengyang wrote: > Help check if my logic is correct in all 5 expressions > > > A) Set bool_one equal to the result of > False and False > > Entire Expression : False and False gives True because both are False This is not correct, and comes from a confusion in the English language. In boolean logic, "and" means "both". For instance: *IF* we have eggs, *AND* we have bacon, *THEN* bake a pie. Can you bake an egg-and-bacon pie? You need *both* ingredients. The assertion "we have eggs" is True if we do and False if we do not; and the overall condition cannot be True unless *both* assertions are True. In Python, the second half won't even be looked at if the first half is false. That is to say, Python looks beside the stove to see if there's a carton of eggs, and if it can't see one, it won't bother looking in the freezer for bacon - it already knows we can't bake that pie. Your other questions are derived from this one, so you should be fine once you grok this one concept. ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Boolean Expressions
On Tuesday, September 26, 2017 at 2:54:32 PM UTC-7, Chris Angelico wrote: > On Wed, Sep 27, 2017 at 7:43 AM, Cai Gengyang wrote: > > Help check if my logic is correct in all 5 expressions > > > > > > A) Set bool_one equal to the result of > > False and False > > > > Entire Expression : False and False gives True because both are False > > This is not correct, and comes from a confusion in the English > language. In boolean logic, "and" means "both". For instance: > > *IF* we have eggs, *AND* we have bacon, *THEN* bake a pie. > > Can you bake an egg-and-bacon pie? You need *both* ingredients. The > assertion "we have eggs" is True if we do and False if we do not; and > the overall condition cannot be True unless *both* assertions are > True. > > In Python, the second half won't even be looked at if the first half > is false. That is to say, Python looks beside the stove to see if > there's a carton of eggs, and if it can't see one, it won't bother > looking in the freezer for bacon - it already knows we can't bake that > pie. > > Your other questions are derived from this one, so you should be fine > once you grok this one concept. > > ChrisA A way to prove this: def funcA(): print('In function A') return False def funcB(): print('In function B') return False print(funcA() and funcB()) This will print 'In function A' followed by 'False'. It will not print 'In function B' at all. -- https://mail.python.org/mailman/listinfo/python-list
Re: Boolean Expressions
I'm trying to understand the logic behind AND. I looked up Python logic tables False and False gives False False and True gives False True and False gives False True and True gives True. So does that mean that the way 'and' works in Python is that both terms must be True (1) for the entire expression to be True ? Why is it defined that way, weird ? I was always under the impression that 'and' means that when you have both terms the same, ie either True and True or False and False , then it gives True On Wednesday, September 27, 2017 at 5:54:32 AM UTC+8, Chris Angelico wrote: > On Wed, Sep 27, 2017 at 7:43 AM, Cai Gengyang wrote: > > Help check if my logic is correct in all 5 expressions > > > > > > A) Set bool_one equal to the result of > > False and False > > > > Entire Expression : False and False gives True because both are False > > This is not correct, and comes from a confusion in the English > language. In boolean logic, "and" means "both". For instance: > > *IF* we have eggs, *AND* we have bacon, *THEN* bake a pie. > > Can you bake an egg-and-bacon pie? You need *both* ingredients. The > assertion "we have eggs" is True if we do and False if we do not; and > the overall condition cannot be True unless *both* assertions are > True. > > In Python, the second half won't even be looked at if the first half > is false. That is to say, Python looks beside the stove to see if > there's a carton of eggs, and if it can't see one, it won't bother > looking in the freezer for bacon - it already knows we can't bake that > pie. > > Your other questions are derived from this one, so you should be fine > once you grok this one concept. > > ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Boolean Expressions
On 09/26/2017 03:23 PM, Cai Gengyang wrote: I'm trying to understand the logic behind AND. I looked up Python logic tables False and False gives False False and True gives False True and False gives False True and True gives True. So does that mean that the way 'and' works in Python is that both terms must be True (1) for the entire expression to be True ? Why is it defined that way, weird ? I was always under the impression that 'and' means that when you have both terms the same, ie either True and True or False and False , then it gives True No, that would actually be an xnor (not xor) operation, a fairly rare usage case. Python doesn't even provide an operator for that, the closest thing would be (bool(x) == bool(y)). "And" means "and". This is true AND that is true. -- Rob Gaddi, Highland Technology -- www.highlandtechnology.com Email address domain is currently out of order. See above to fix. -- https://mail.python.org/mailman/listinfo/python-list
Re: Boolean Expressions
On 26Sep2017 14:43, Cai Gengyang wrote: Help check if my logic is correct in all 5 expressions Why not just run some code interactively? Unless this is entirely a thought exercise to verify that you have a solid mental understanding of Python semantics, all your reasoning is easy to test. In order to be honest to yourself, you could write does all your answers (exactly as you have just done), _then_ go and run the expressions by hand in python to see which are correct. You can also run the subparts of the expressions, so that you can see which you have misevaluated versus which you have made correct/incorrect logic reasoning about. A) Set bool_one equal to the result of False and False Entire Expression : False and False gives True because both are False No. False and anything gives False. An "and" only gives True if both sides are true. B) Set bool_two equal to the result of -(-(-(-2))) == -2 and 4 >= 16 ** 0.5 -(-(-(-2))) is equal to 2, and 2 is not equal to -2, hence the first term -(-(-(-2))) == -2 is False. 4 >= 16 ** 0.5 is True because 16 ** 0.5 is equal to 4, and 4 is greater then or equal to 4, hence the 2nd term 4 >= 16 ** 0.5 is True. Entire expression : False because False and True gives False In python, "and" and "or" short circuit. So if you know enough to evaluate the condition from the left hand side, the right hand side is not evaluated at all. So since 2 == -2 gives False, the expresion is False and the right hand is not evaluated. Note, BTW, that 16 ** 0.5 returns a floating point value. While that particular example works nicely, probably because it is all powers of 2 and doesn't hit rounding issues, testing equality with floating point is a dangerous area. C) Set bool_three equal to the result of 19 % 4 != 300 / 10 / 10 and False 19 % 4 = 3 which is equal to 300 / 10 / 10 = 3, hence the first term is False. Entire expression is then equal to True, because False and False = True Entire expression is False because the left hand side is False. D) Set bool_four equal to the result of -(1 ** 2) < 2 ** 0 and 10 % 10 <= 20 - 10 * 2 -(1 ** 2) is equal to -1 , which is less than 2 ** 0 = 1, hence the first term is True. 2nd term 10 % 10 is equal to 0 , which is less than or equal to 20 - 10 * 2 , hence 2nd term is True. Entire expression : True and True = True Correct. (In my head; haven't run the code.) E) Set bool_five equal to the result of True and True Entire Expression : True and True = True Correct. Cheers, Cameron Simpson ERROR 155 - You can't do that. - Data General S200 Fortran error code list -- https://mail.python.org/mailman/listinfo/python-list
Re: Boolean Expressions
On 26Sep2017 15:23, Cai Gengyang wrote: I'm trying to understand the logic behind AND. I looked up Python logic tables False and False gives False False and True gives False True and False gives False True and True gives True. So does that mean that the way 'and' works in Python is that both terms must be True (1) for the entire expression to be True ? Yes. Why is it defined that way, weird ? I was always under the impression that 'and' means that when you have both terms the same, ie either True and True or False and False , then it gives True I would have called this "not the same". You are describing "or". "and" means "both true". "or" means "either true". An "and" expression is true if the left half is true _and_ the right half is true. Therefore both must be true, otherwise the whole result is false. An "or" expression is true if the left half is true _or_ the right half is true, therefore only one half needs to be true. You only get 'false" is both halves are false. Think of "and" a little like multiplication with values or 0 (false) and 1 (true). Think of "or" a little like addition with values of 0 (false) and 1 (true). And: 1 * 1 => nonzero/true 1 * 0 => zero/false 0 * 1 => zero/false 0 * 0 => zero/false Or: 1 + 1 => nonzero/true 1 + 0 => nonzero/true 0 + 1 => nonzero/true 0 + 0 => zero/false If all this seems confusing I wonder about your understanding of the plain English words "and" and "or", but your English seems otherwise perfectly fine to me, so that would be very surprising. Can you write some plain English sentences where "and" or "or" lead you to misinterpret a similar Python expression? Then we can see where the differences lie. Cheers, Cameron Simpson (formerly c...@zip.com.au) -- https://mail.python.org/mailman/listinfo/python-list
Re: Boolean Expressions
On 09/27/2017 12:23 AM, Cai Gengyang wrote: > > I'm trying to understand the logic behind AND. I looked up Python logic tables > > False and False gives False > False and True gives False > True and False gives False > True and True gives True. > > So does that mean that the way 'and' works in Python is that both terms must > be True (1) for the entire expression to be True ? Why is it defined that > way, weird ? I was always under the impression that 'and' means that when you > have both terms the same, ie either True and True or False and False , then > it gives True There is nothing Python specific about this, by the way. It is how AND - ∧ - has been defined in Boolean Algebra forever. It's a logical conjunction of its operands, it doesn't test for the 'equality' of its operands. https://en.wikipedia.org/wiki/Logical_conjunction Irmen -- https://mail.python.org/mailman/listinfo/python-list
Re: Boolean Expressions
> > On Sep 26, 2017, at 3:23 PM, Cai Gengyang wrote: > > > I'm trying to understand the logic behind AND. I looked up Python logic tables > > False and False gives False > False and True gives False > True and False gives False > True and True gives True. > > So does that mean that the way 'and' works in Python is that both terms must > be True (1) for the entire expression to be True ? Why is it defined that > way, weird ? I was always under the impression that 'and' means that when you > have both terms the same, ie either True and True or False and False , then > it gives True > > As others have said, this is about the definition of the "and" operator. One example I give in my class is this: At the local amusement park there is a sign that says, "You must be at least 12 years old and at least 48 inches tall to ride the roller coaster". That means that both conditions must be true in order for you to get on the roller coaster. The Python code would be: if (age >= 12) and (height >= 48): # You are good to go It would be evaluated like this: If you are 5 years old (first condition is false) and you are only 36 inches tall (second condition is false), you cannot get on the roller coaster. Logically: False and False is False If you are 20 years old (true) but only 30 inches tall (false), you cannot get on the roller coaster Logically: True and False is False If you are 10 years old (false) but you are 75 inches tall (true), you may be a freak of nature, but you cannot get on the roller coaster. Logically: False and True is False If you are 13 years old (true) and 51 inches tall (true), enjoy your ride Logically: True and True is True Bottom line, "and" operates between two Booleans. "and" only give you a True as a result, when both side of the "and" are True. Irv PS: The "or" operator works like this: If any of the inputs is True, then the result of doing an "or" is True. The only case where "or' gives you a False, is when all the inputs are False. -- https://mail.python.org/mailman/listinfo/python-list
Re: Boolean Expressions
On 27/09/17 00:23, Cai Gengyang wrote: > I'm trying to understand the logic behind AND. I looked up Python logic tables > > False and False gives False > False and True gives False > True and False gives False > True and True gives True. > > So does that mean that the way 'and' works in Python is that both terms must > be True (1) for the entire expression to be True ? Why is it defined that > way, weird ? I was always under the impression that 'and' means that when you > have both terms the same, ie either True and True or False and False , then > it gives True What gave you that impression? This is the way "and" is defined in formal logic, electronics, programming, and all languages that I know. no and no does not mean yes. (There may be ambiguity in what precisely "or" means in English, but "and" is pretty clear...) The logical operation you're thinking of is sometimes called "XNOR". One way to write this in Python is bool(a) == bool(b) Python 3.5.3 (default, Jan 19 2017, 14:11:04) [GCC 6.3.0 20170118] on linux Type "help", "copyright", "credits" or "license" for more information. >>> def xnor(a, b): ... return bool(a) == bool(b) ... >>> xnor(True, True) True >>> xnor(True, False) False >>> xnor(False, False) True >>> xnor(False, True) False >>> > > > > > > On Wednesday, September 27, 2017 at 5:54:32 AM UTC+8, Chris Angelico wrote: >> On Wed, Sep 27, 2017 at 7:43 AM, Cai Gengyang wrote: >>> Help check if my logic is correct in all 5 expressions >>> >>> >>> A) Set bool_one equal to the result of >>> False and False >>> >>> Entire Expression : False and False gives True because both are False >> This is not correct, and comes from a confusion in the English >> language. In boolean logic, "and" means "both". For instance: >> >> *IF* we have eggs, *AND* we have bacon, *THEN* bake a pie. >> >> Can you bake an egg-and-bacon pie? You need *both* ingredients. The >> assertion "we have eggs" is True if we do and False if we do not; and >> the overall condition cannot be True unless *both* assertions are >> True. >> >> In Python, the second half won't even be looked at if the first half >> is false. That is to say, Python looks beside the stove to see if >> there's a carton of eggs, and if it can't see one, it won't bother >> looking in the freezer for bacon - it already knows we can't bake that >> pie. >> >> Your other questions are derived from this one, so you should be fine >> once you grok this one concept. >> >> ChrisA -- https://mail.python.org/mailman/listinfo/python-list
Re: Boolean Expressions
On Wed, 27 Sep 2017 08:23 am, Cai Gengyang wrote: > > I'm trying to understand the logic behind AND. I looked up Python logic tables > > False and False gives False > False and True gives False > True and False gives False > True and True gives True. > > So does that mean that the way 'and' works in Python is that both terms must > be True (1) for the entire expression to be True ? Why is it defined that way, > weird ? I was always under the impression that 'and' means that when you have > both terms the same, ie either True and True or False and False , then it > gives True No, your impression is wrong. Python's AND is the same as boolean AND everywhere: every programming language that supports boolean AND, in Boolean Algebra and in logic. In C++ https://msdn.microsoft.com/en-us/library/c6s3h5a7.aspx In Javascript https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators Boolean algebra https://en.wikipedia.org/wiki/Boolean_algebra#Basic_operations Consider that today I spent the day sitting at home watching movies. If I said: "Today, I climbed to the top of Mount Everest." That would be False. If I said: "Today, I swam across the English Channel." That would be False. If I said: "Today, I climbed to the top of Mount Everest, AND I swam across the English Channel." that is still False. What you are thinking of is best describes as "equals": False equals False gives True False equals True gives False True equals False gives False True equals True gives True -- Steve “Cheer up,” they said, “things could be worse.” So I cheered up, and sure enough, things got worse. -- https://mail.python.org/mailman/listinfo/python-list
Re: Boolean Expressions
On Wednesday, September 27, 2017 at 6:45:00 AM UTC+8, Cameron Simpson wrote: > On 26Sep2017 14:43, Cai Gengyang wrote: > >Help check if my logic is correct in all 5 expressions > > Why not just run some code interactively? Unless this is entirely a thought > exercise to verify that you have a solid mental understanding of Python > semantics, all your reasoning is easy to test. > > In order to be honest to yourself, you could write does all your answers > (exactly as you have just done), _then_ go and run the expressions by hand in > python to see which are correct. You can also run the subparts of the > expressions, so that you can see which you have misevaluated versus which you > have made correct/incorrect logic reasoning about. > > >A) Set bool_one equal to the result of > >False and False > > > >Entire Expression : False and False gives True because both are False > > No. False and anything gives False. An "and" only gives True if both sides > are > true. > > >B) Set bool_two equal to the result of > >-(-(-(-2))) == -2 and 4 >= 16 ** 0.5 > > > >-(-(-(-2))) is equal to 2, and 2 is not equal to -2, hence the first term > > -(-(-(-2))) == -2 is False. 4 >= 16 ** 0.5 is True because 16 ** 0.5 is > >equal to 4, and 4 is greater then or equal to 4, hence the 2nd term 4 >= 16 > >** 0.5 is True. > > > >Entire expression : False because False and True gives False > > In python, "and" and "or" short circuit. So if you know enough to evaluate > the > condition from the left hand side, the right hand side is not evaluated at > all. > > So since 2 == -2 gives False, the expresion is False and the right hand is > not > evaluated. > > Note, BTW, that 16 ** 0.5 returns a floating point value. While that > particular > example works nicely, probably because it is all powers of 2 and doesn't hit > rounding issues, testing equality with floating point is a dangerous area. > > >C) Set bool_three equal to the result of > >19 % 4 != 300 / 10 / 10 and False > > > >19 % 4 = 3 which is equal to 300 / 10 / 10 = 3, hence the first term is > >False. Entire expression is then equal to True, because False and False = > >True > > Entire expression is False because the left hand side is False. > > >D) Set bool_four equal to the result of > >-(1 ** 2) < 2 ** 0 and 10 % 10 <= 20 - 10 * 2 > > > >-(1 ** 2) is equal to -1 , which is less than 2 ** 0 = 1, hence the first > >term is True. 2nd term 10 % 10 is equal to 0 , which is less than or equal > >to 20 - 10 * 2 , hence 2nd term is True. > > > >Entire expression : True and True = True > > Correct. (In my head; haven't run the code.) > > >E) Set bool_five equal to the result of > >True and True > > > >Entire Expression : True and True = True > > Correct. > > Cheers, > Cameron Simpson > > ERROR 155 - You can't do that. - Data General S200 Fortran error code list > 19 % 4 = 3 which is equal to 300 / 10 / 10 = 3, hence the first term is > False. Entire expression is then equal to True, because False and False = True > > Entire expression is False because the left hand side is False. Am I missing something here ? 19 % 4 = 19 modulo 4 equals to 3 right ? which equals the right hand side , hence first term is True -- https://mail.python.org/mailman/listinfo/python-list
Re: Boolean Expressions
Cai Gengyang wrote: So does that mean that the way 'and' works in Python is that both terms must be True (1) for the entire expression to be True ? Why is it defined that way, weird ? It's not weird, it's the normal meaning of "and" in English. Do I have purple hair? No. Do I have three nostrils? No. Do I have purple hair AND three nostrils? No. If the answer to the third question were "yes" given the first two, *that* would be weird. -- Greg -- https://mail.python.org/mailman/listinfo/python-list
Re: Boolean Expressions
On 26Sep2017 20:55, Cai Gengyang wrote: On Wednesday, September 27, 2017 at 6:45:00 AM UTC+8, Cameron Simpson wrote: On 26Sep2017 14:43, Cai Gengyang wrote: >C) Set bool_three equal to the result of >19 % 4 != 300 / 10 / 10 and False > 19 % 4 = 3 which is equal to 300 / 10 / 10 = 3, hence the first term is False. Entire expression is then equal to True, because False and False = True Entire expression is False because the left hand side is False. Am I missing something here ? 19 % 4 = 19 modulo 4 equals to 3 right ? which equals the right hand side , hence first term is True But the test is for "!=", not "==". So False. Cheers, Cameron Simpson (formerly c...@zip.com.au) -- https://mail.python.org/mailman/listinfo/python-list
Re: Boolean Expressions
On Wednesday, September 27, 2017 at 1:01:50 PM UTC+8, Cameron Simpson wrote: > On 26Sep2017 20:55, Cai Gengyang wrote: > >On Wednesday, September 27, 2017 at 6:45:00 AM UTC+8, Cameron Simpson wrote: > >> On 26Sep2017 14:43, Cai Gengyang wrote: > >> >C) Set bool_three equal to the result of > >> >19 % 4 != 300 / 10 / 10 and False > >> > > >> 19 % 4 = 3 which is equal to 300 / 10 / 10 = 3, hence the first term is > >> False. Entire expression is then equal to True, because False and False = > >> True > >> > >> Entire expression is False because the left hand side is False. > > > >Am I missing something here ? 19 % 4 = 19 modulo 4 equals to 3 right ? which > >equals the right hand side , hence first term is True > > But the test is for "!=", not "==". So False. > > Cheers, > Cameron Simpson (formerly c...@zip.com.au) Right ... I didn't see the ' =! ' -- https://mail.python.org/mailman/listinfo/python-list
Re: Boolean Expressions
On Wed, Sep 27, 2017 at 5:21 AM, Cai Gengyang wrote: > On Wednesday, September 27, 2017 at 1:01:50 PM UTC+8, Cameron Simpson > wrote: > > On 26Sep2017 20:55, Cai Gengyang wrote: > > >On Wednesday, September 27, 2017 at 6:45:00 AM UTC+8, Cameron Simpson > wrote: > > >> On 26Sep2017 14:43, Cai Gengyang wrote: > > >> >C) Set bool_three equal to the result of > > >> >19 % 4 != 300 / 10 / 10 and False > > >> > > > >> 19 % 4 = 3 which is equal to 300 / 10 / 10 = 3, hence the first term > is > > >> False. Entire expression is then equal to True, because False and > False = > > >> True > > >> > > >> Entire expression is False because the left hand side is False. > > > > > >Am I missing something here ? 19 % 4 = 19 modulo 4 equals to 3 right ? > which > > >equals the right hand side , hence first term is True > > > > But the test is for "!=", not "==". So False. > > > > Cheers, > > Cameron Simpson (formerly c...@zip.com.au) > > Right ... I didn't see the ' =! ' > -- > You didn't see the '!=' -- Joel Goldstick http://joelgoldstick.com/blog http://cc-baseballstats.info/stats/birthdays -- https://mail.python.org/mailman/listinfo/python-list
Understanding Boolean Expressions
Hello. I am new to this group. I've done a search for the topic about which I'm posting, and while I have found some threads that are relevant, I haven't found anything exactly on point that I can understand. So, I'm taking the liberty of asking about something that may be obvious to many readers of this group. The relevant Python documentation reference is: http://docs.python.org/2/reference/expressions.html#boolean-operations. I'm trying to make sense of the rules of or_test, and_test, and not_test that appear in this section. While I understand the substance of the text in this section, it is the grammar definitions themselves that confuse me. For example, I am not clear how an or_test can be an and_test. Moreover, if I follow the chain of non-terminal references, I move from or_test, to and_test, to not_test, to comparison. And when I look at the definition for comparison, I seem to be into bitwise comparisons. I cannot explain this. Perhaps an example will help put my confusion into more concrete terms. Suppose I write the expression if x or y in my code. I presume this is an example of an or_test. Beyond that, though, I'm not sure whether this maps to an and_test (the first option on the right-hand side of the rule) or to the or_test "or" and_test option (the second on the right-hand side of the rule). If people can offer some thoughts to put me in the right direction (or out of my misery), I would appreciate it. Thank you in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: Understanding Boolean Expressions
On Tue, 16 Apr 2013 15:19:25 -0700, Bruce McGoveran wrote: > Hello. I am new to this group. I've done a search for the topic about > which I'm posting, and while I have found some threads that are > relevant, I haven't found anything exactly on point that I can > understand. So, I'm taking the liberty of asking about something that > may be obvious to many readers of this group. > > The relevant Python documentation reference is: > http://docs.python.org/2/reference/expressions.html#boolean-operations. > > I'm trying to make sense of the rules of or_test, and_test, and not_test > that appear in this section. While I understand the substance of the > text in this section, it is the grammar definitions themselves that > confuse me. For example, I am not clear how an or_test can be an > and_test. Moreover, if I follow the chain of non-terminal references, I > move from or_test, to and_test, to not_test, to comparison. And when I > look at the definition for comparison, I seem to be into bitwise > comparisons. I cannot explain this. > > Perhaps an example will help put my confusion into more concrete terms. > Suppose I write the expression if x or y in my code. I presume this is > an example of an or_test. Beyond that, though, I'm not sure whether > this maps to an and_test (the first option on the right-hand side of the > rule) or to the or_test "or" and_test option (the second on the > right-hand side of the rule). > > If people can offer some thoughts to put me in the right direction (or > out of my misery), I would appreciate it. $ python Python 2.7.3 (default, Jan 15 2013, 02:26:36) [GCC 4.2.1 20070831 patched [FreeBSD]] on freebsd9 Type "help", "copyright", "credits" or "license" for more information. >>> not True False >>> not False True >>> True or False True >>> True and False False >>> x = 2 >>> not (x == 2) False >>> not (x == 3) True >>> x == 2 True >>> x == 3 False >>> -- http://mail.python.org/mailman/listinfo/python-list
Re: Understanding Boolean Expressions
On 04/16/2013 06:19 PM, Bruce McGoveran wrote: Hello. I am new to this group. I've done a search for the topic about which I'm posting, and while I have found some threads that are relevant, I haven't found anything exactly on point that I can understand. So, I'm taking the liberty of asking about something that may be obvious to many readers of this group. The relevant Python documentation reference is: http://docs.python.org/2/reference/expressions.html#boolean-operations. I'm trying to make sense of the rules of or_test, and_test, and not_test that appear in this section. While I understand the substance of the text in this section, it is the grammar definitions themselves that confuse me. For example, I am not clear how an or_test can be an and_test. Moreover, if I follow the chain of non-terminal references, I move from or_test, to and_test, to not_test, to comparison. And when I look at the definition for comparison, I seem to be into bitwise comparisons. I cannot explain this. Perhaps an example will help put my confusion into more concrete terms. Suppose I write the expression if x or y in my code. I presume this is an example of an or_test. Beyond that, though, I'm not sure whether this maps to an and_test (the first option on the right-hand side of the rule) or to the or_test "or" and_test option (the second on the right-hand side of the rule). If people can offer some thoughts to put me in the right direction (or out of my misery), I would appreciate it. It's been decades since I really had to understand a complete grammar. But in some ways, a fragment like you're referencing is even harder. The trick is to take those names "and_test" as rather arbitrary. There's no token meaning "an expression containing 4 or's, 2 and's, and 1 not" So sometimes the terms used are rather silly looking. The point is you can combine 'not', 'and', 'or', and comparison operators like ==, >= etc. in some complex ways. The grammar just says which of these is legal, and doesn't help you figure out the semantics, which is usually much more important to you and me. First, nearly all objects have a 'truth' value, for which I use the terms 'true' and 'false'. For numbers, nonzero values are true, and zero values are false. For collections, nonempty collections are true and empty ones are false. And so on. So if x is an int, and if you say: if x: You're checking the 'truth' of x, and it'll execute the if clause for nonzero integers, for example. If you have an arbitrary object 'x', it is not necessarily of type bool. But if you compare it to another one, x==y the result is a bool, either True or False. Likewise if you apply the unary 'not' to an object; the result will be either True or False. But if you combine two expressions with 'or' the result is NOT necessarily of type bool. If the first expression is true, then the second expression isn't even examined. If the first expression is false, the second expression is the result. 'and' has the reverse meaning. And more complex expressions can be understood by breaking them into steps, according to operator precedence and parentheses. -- DaveA -- http://mail.python.org/mailman/listinfo/python-list
Re: Understanding Boolean Expressions
On Tue, 16 Apr 2013 23:19:25 +0100, Bruce McGoveran wrote: Hello. I am new to this group. I've done a search for the topic about which I'm posting, and while I have found some threads that are relevant, I haven't found anything exactly on point that I can understand. So, I'm taking the liberty of asking about something that may be obvious to many readers of this group. The relevant Python documentation reference is: http://docs.python.org/2/reference/expressions.html#boolean-operations. I'm trying to make sense of the rules of or_test, and_test, and not_test that appear in this section. While I understand the substance of the text in this section, it is the grammar definitions themselves that confuse me. For example, I am not clear how an or_test can be an and_test. Moreover, if I follow the chain of non-terminal references, I move from or_test, to and_test, to not_test, to comparison. And when I look at the definition for comparison, I seem to be into bitwise comparisons. I cannot explain this. Perhaps an example will help put my confusion into more concrete terms. Suppose I write the expression if x or y in my code. I presume this is an example of an or_test. Beyond that, though, I'm not sure whether this maps to an and_test (the first option on the right-hand side of the rule) or to the or_test "or" and_test option (the second on the right-hand side of the rule). If people can offer some thoughts to put me in the right direction (or out of my misery), I would appreciate it. What the grammar rules are giving you is operator precedence -- "not" has higher precedence than "and", which is higher than "or". As you follow the non-terminals back you go further through precedence chain: comparisons, then bitwise operators (*not* bitwise comparisons!), then shifts, then arithmetic operators, the unary operators, the power operator, and finally primaries. -- Rhodri James *-* Wildebeest Herder to the Masses -- http://mail.python.org/mailman/listinfo/python-list
Re: Understanding Boolean Expressions
[2nd try, quotation a bit messed up] On 4/16/2013 6:19 PM, Bruce McGoveran wrote: > Hello. I am new to this group. I've done a search for the topic > about which I'm posting, and while I have found some threads that are > relevant, I haven't found anything exactly on point that I can > understand. So, I'm taking the liberty of asking about something > that may be obvious to many readers of this group. > The relevant Python documentation reference is: > http://docs.python.org/2/reference/expressions.html#boolean-operations. > I'm trying to make sense of the rules of or_test, and_test, and > not_test that appear in this section. While I understand the > substance of the text in this section, The substance is that 1) 'not' binds tighter than 'and' binds tigher than 'or' and 2) 'and' and 'or' both associate left to right in the normal manner so that 'a op b op c' == '(a op b) op c'. > it is the grammar definitions themselves that confuse me. The techinical details reflect the fact that Python's grammar is ll(1) (top-down, parsed by recursive descent) rather than lr(1) (bottom-up). The latter (in lalr(1) form) is what yacc, etc use and might be more familiar to you. > For example, I am not clear how an or_test can be an and_test. or_test ::= and_test | or_test "or" and_test The second option expresses the associativity rule, but more is needed to get out of infinite regress. Substituting the second rule into second rule gives or_test = (or_test 'or' and_test) 'or' and_test and so on. At some point, one must replace or_test with and_test to get an 'or' of ands. Similarly, an and_test must resolve to an 'and' of nots. > Moreover, if I follow the chain of non-terminal references, I move > from or_test, to and_test, to nt_test, to comparison. And when I > look at the definition for comparison, I seem to be into bitwise > comparisons. I cannot explain this. Eventually the chain takes one to primaries, which include things like literals and identifiers. > Perhaps an example will help put my confusion into more concrete terms. Suppose I write the expression if x or y in my code. I presume this is an example of an or_test. Yes. > Beyond that, though, I'm not sure whether this maps to an and_test (the first option on the right-hand side of the rule) or to the or_test "or" and_test option (the second on the right-hand side of the rule). The second. Then the or_test on the left also maps to an and_test. Each and_test eventually resolves to 'identifier', specifically 'x' and 'y'. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: Understanding Boolean Expressions
Thank you all for thoughts. I'm just about to post another question about atoms and primaries. If you have a moment to look it over, I would appreciate your thoughts. Many thanks in advance. On Tuesday, April 16, 2013 6:19:25 PM UTC-4, Bruce McGoveran wrote: > Hello. I am new to this group. I've done a search for the topic about which > I'm posting, and while I have found some threads that are relevant, I haven't > found anything exactly on point that I can understand. So, I'm taking the > liberty of asking about something that may be obvious to many readers of this > group. > > > > The relevant Python documentation reference is: > http://docs.python.org/2/reference/expressions.html#boolean-operations. > > > > I'm trying to make sense of the rules of or_test, and_test, and not_test that > appear in this section. While I understand the substance of the text in this > section, it is the grammar definitions themselves that confuse me. For > example, I am not clear how an or_test can be an and_test. Moreover, if I > follow the chain of non-terminal references, I move from or_test, to > and_test, to not_test, to comparison. And when I look at the definition for > comparison, I seem to be into bitwise comparisons. I cannot explain this. > > > > Perhaps an example will help put my confusion into more concrete terms. > Suppose I write the expression if x or y in my code. I presume this is an > example of an or_test. Beyond that, though, I'm not sure whether this maps > to an and_test (the first option on the right-hand side of the rule) or to > the or_test "or" and_test option (the second on the right-hand side of the > rule). > > > > If people can offer some thoughts to put me in the right direction (or out of > my misery), I would appreciate it. > > > > Thank you in advance. -- http://mail.python.org/mailman/listinfo/python-list
Re: Understanding Boolean Expressions
On Tue, 16 Apr 2013 15:19:25 -0700, Bruce McGoveran wrote: > Hello. I am new to this group. I've done a search for the topic about > which I'm posting, and while I have found some threads that are > relevant, I haven't found anything exactly on point that I can > understand. So, I'm taking the liberty of asking about something that > may be obvious to many readers of this group. > > The relevant Python documentation reference is: > http://docs.python.org/2/reference/expressions.html#boolean-operations. > > I'm trying to make sense of the rules of or_test, and_test, and not_test > that appear in this section. While I understand the substance of the > text in this section, it is the grammar definitions themselves that > confuse me. For example, I am not clear how an or_test can be an > and_test. In this case, you could have saved us some time by copying and pasting the relevant three lines: or_test ::= and_test | or_test "or" and_test and_test ::= not_test | and_test "and" not_test not_test ::= comparison | "not" not_test I agree that this is not entirely the most obvious wording, but it makes a sort of sense if you follow it through carefully. Unfortunately, to really understand the grammar, you have to follow through the entire thing. But translated into English, the above three rules might read like this: An expression which we call an or_test can be either: 1) an and_test; or 2) another or_test, followed by the literal string "or", followed by an and_test. An expression which we call an and_test can be either: 3) a not_test; or 4) another and_test, followed by the literal string "and", followed by another not_test. An expression which we call a not_test can be either: 5) a comparison; or 6) the literal string "not", followed by another not_test. An expression which we call a comparison can be: ... a bunch more different alternatives, going through bitwise comparisons, then arithmetic operators, then other expressions, and so on, until finally you reach the simplest expressions possible, names and constant literals. So in a sense, an "or_test" does not JUST mean it's a test with an "or" in it. The thing called an or_test is an and_test *or* a test with an "or" in it; an and_test is a not_test *or* a test with an "and" in it; a not_test is a comparison *or* a test with a "not" in it; a comparison is ... and so forth, until you run out of expressions and end up with a simple atom like a name or a constant. So paradoxically, that means that "x or y" counts as an and_test (obviously!) but also as an or_test, since every and_test also counts as an or_test. Here's some crappy ASCII art of a Venn diagram with a couple of examples shown: (best viewed in a fixed-width font): +-+ | or_tests | | "x or y" | |+--+ | || and_tests | | ||"x and y" | | ||+-+ | | ||| not_tests | | | ||| | | | ||| "not x" | | | ||+-+ | | |+--+ | +-+ Inside the "not_test" box, not shown, are other boxes relating to other expressions, and ending deep down with boxes labelled "names" and "literals". (Or so I expect, since I haven't followed the maze of twisty grammar rules, all alike, to the very end.) Of course, in practice we wouldn't normally call an expression such as "x and y" as an or_test, even though strictly speaking the grammar says it is. We would call it by the smallest box it is contained within, namely "and_test". An analogy: normally, we would refer to Python's creator Guido van Rossum as a "man", not a "mammal", but since all men are mammals, it wouldn't be wrong to call him such. But not all mammals are men, and not all or_tests are and_tests. "x or y" is an or_test, obviously, but not an and_test. Does this help explain it? > Perhaps an example will help put my confusion into more concrete terms. > Suppose I write the expression if x or y in my code. I presume this is > an example of an or_test. Beyond that, though, I'm not sure whether > this maps to an and_test (the first option on the right-hand side of the > rule) or to the or_test "or" and_test option (the second on the > right-hand side of the rule). "x or y" maps to the second option. The "x" matches and_test, which then matches not_test, which then matches comparison, which ... blah blah blah ... which finally matches a plain name. The "or" matches the literal string "or" in the grammar rule. Then the "y" matches and_test, which ... finally matches a plain name. Of course, this is NOT necessarily what Python does every time it parses a piece of code! It's just a description of the grammar. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Understanding Boolean Expressions
Steven D'Aprano writes: > So paradoxically, that means that "x or y" counts as an and_test > (obviously!) but also as an or_test, since every and_test also > counts as an or_test. Here's some crappy ASCII art of a Venn diagram I think you mean to say that "x and y" counts as an and_test and also as an or_test. -- http://mail.python.org/mailman/listinfo/python-list
Re: Understanding Boolean Expressions
On Wed, 17 Apr 2013 11:47:49 +0300, Jussi Piitulainen wrote: > Steven D'Aprano writes: > >> So paradoxically, that means that "x or y" counts as an and_test >> (obviously!) but also as an or_test, since every and_test also counts >> as an or_test. Here's some crappy ASCII art of a Venn diagram > > I think you mean to say that "x and y" counts as an and_test and also as > an or_test. You may very well be right, but I'll be damned if I go back and read through my post trying to work out what I intended to say instead of what I actually said! :-) And-or-or-and-or-or-or-and-and-or-ly y'rs, -- Steven -- http://mail.python.org/mailman/listinfo/python-list
Re: Understanding Boolean Expressions
Steven D'Aprano writes: > On Wed, 17 Apr 2013 11:47:49 +0300, Jussi Piitulainen wrote: > > > Steven D'Aprano writes: > > > >> So paradoxically, that means that "x or y" counts as an and_test > >> (obviously!) but also as an or_test, since every and_test also counts > >> as an or_test. Here's some crappy ASCII art of a Venn diagram > > > > I think you mean to say that "x and y" counts as an and_test and also as > > an or_test. > > You may very well be right, but I'll be damned if I go back and read > through my post trying to work out what I intended to say instead of what > I actually said! > > :-) The quote above is sufficient context for one who knows that "x or y" is not an and_test. I'm hoping that pointing this little thing out will help some potentially confused reader of your otherwise excellent explanation see more quickly that this is really just a harmless typo. (Unless it's me who's confused :) The quote appeared just before your ASCII art. -- http://mail.python.org/mailman/listinfo/python-list
Best way to evaluate boolean expressions from strings?
Hello, everybody. I need to evaluate boolean expressions like "foo == 1" or "foo ==1 and (bar > 2 or bar == 0)" which are defined as strings (in a database or a plain text file, for example). How would you achieve this? These expressions will contain placeholders for Python objects (like "foo" and "bar" in the examples above). Also, the Python objects that will get injected in the expression will support at least one of the following operations: "==", "!=", ">", "<", ">=", "<=", "&", "|", "in". I don't need the ability to import modules, define classes, define functions, etc. I just need to evaluate boolean expressions defined as strings (using the Python syntax is fine, or even desirable). Here's a complete example: I have the "user_ip" and "valid_ips" placeholders defined in Python as follows: """ user_ip = '111.111.111.111' class IPCollection(object): def __init__(self, *valid_ips): self.valid_ips = valid_ips def __contains__(self, value): return value in self.valid_ips valid_ips = IPCollection('222.222.222.222', '111.111.111.111') """ So the following boolean expressions given as strings should be evaluated as: * "user_ip == '127.0.0.1'" ---> False * "user_ip == '127.0.0.1' or user_ip in valid_ips" ---> True * "user_ip not in valid_ips" ---> False That's it. How would you deal with this? I would love to re-use existing stuff as much as possible, that works in Python 2.4-2.6 and also that has a simple syntax (these expressions may not be written by technical people; hence I'm not sure about using TALES). Thanks in advance! -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to evaluate boolean expressions from strings?
En Mon, 27 Apr 2009 14:03:01 -0300, Gustavo Narea escribió: I need to evaluate boolean expressions like "foo == 1" or "foo ==1 and (bar > 2 or bar == 0)" which are defined as strings (in a database or a plain text file, for example). How would you achieve this? This recent thread may be of interest: Safe eval of moderately simple math expressions http://groups.google.com/group/comp.lang.python/t/c1aff28494ab5b59/ -- Gabriel Genellina -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to evaluate boolean expressions from strings?
Gustavo Narea wrote: > I need to evaluate boolean expressions like "foo == 1" or "foo ==1 and > (bar > 2 or bar == 0)" which are defined as strings (in a database or > a plain text file, for example). How would you achieve this? > > These expressions will contain placeholders for Python objects (like > "foo" and "bar" in the examples above). Also, the Python objects that > will get injected in the expression will support at least one of the > following operations: "==", "!=", ">", "<", ">=", "<=", "&", "|", > "in". > > I don't need the ability to import modules, define classes, define > functions, etc. I just need to evaluate boolean expressions defined as > strings (using the Python syntax is fine, or even desirable). > > Here's a complete example: > > I have the "user_ip" and "valid_ips" placeholders defined in Python as > follows: > """ > user_ip = '111.111.111.111' > > class IPCollection(object): > def __init__(self, *valid_ips): > self.valid_ips = valid_ips > def __contains__(self, value): > return value in self.valid_ips > > valid_ips = IPCollection('222.222.222.222', '111.111.111.111') > """ > > So the following boolean expressions given as strings should be > evaluated as: > * "user_ip == '127.0.0.1'" ---> False > * "user_ip == '127.0.0.1' or user_ip in valid_ips" ---> True > * "user_ip not in valid_ips" ---> False > > That's it. How would you deal with this? I would love to re-use > existing stuff as much as possible, that works in Python 2.4-2.6 and > also that has a simple syntax (these expressions may not be written by > technical people; hence I'm not sure about using TALES). exprs = [ "user_ip == '127.0.0.1'", "user_ip == '127.0.0.1' or user_ip in valid_ips", "user_ip not in valid_ips"] for expr in exprs: print expr, "-->", eval(expr) Be warned that a malicious user can make your program execute arbitrary python code; if you put the input form for expressions on the internet you're toast. Peter -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to evaluate boolean expressions from strings?
Thank you very much, Gabriela and Peter! I'm going for Pyparsing. :) -- Gustavo. -- http://mail.python.org/mailman/listinfo/python-list
Re: Best way to evaluate boolean expressions from strings?
Gustavo Narea writes: > Hello, everybody. > > I need to evaluate boolean expressions like "foo == 1" or "foo ==1 and > (bar > 2 or bar == 0)" which are defined as strings (in a database or > a plain text file, for example). How would you achieve this? > > These expressions will contain placeholders for Python objects (like > "foo" and "bar" in the examples above). Also, the Python objects that > will get injected in the expression will support at least one of the > following operations: "==", "!=", ">", "<", ">=", "<=", "&", "|", > "in". > > I don't need the ability to import modules, define classes, define > functions, etc. I just need to evaluate boolean expressions defined as > strings (using the Python syntax is fine, or even desirable). > > Here's a complete example: > > I have the "user_ip" and "valid_ips" placeholders defined in Python as > follows: > """ > user_ip = '111.111.111.111' > > class IPCollection(object): > def __init__(self, *valid_ips): > self.valid_ips = valid_ips > def __contains__(self, value): > return value in self.valid_ips > > valid_ips = IPCollection('222.222.222.222', '111.111.111.111') > """ > > So the following boolean expressions given as strings should be > evaluated as: > * "user_ip == '127.0.0.1'" ---> False > * "user_ip == '127.0.0.1' or user_ip in valid_ips" ---> True > * "user_ip not in valid_ips" ---> False > > That's it. How would you deal with this? I would love to re-use > existing stuff as much as possible, that works in Python 2.4-2.6 and > also that has a simple syntax (these expressions may not be written by > technical people; hence I'm not sure about using TALES). > > Thanks in advance! Here is a proof of concept using the ast module (Python >= 2.6): import ast class UnsafeError(Exception): pass class SafetyChecker(ast.NodeVisitor): def __init__(self, allowed_nodes, allowed_names): self.allowed_nodes = allowed_nodes self.allowed_names = allowed_names def visit(self, node): if isinstance(node, ast.Name): if node.id in self.allowed_names: return raise UnsafeError('unsafe name: %s' % node.id) if type(node) not in self.allowed_nodes: if not any(tp in self.allowed_nodes for tp in type(node).__bases__): raise UnsafeError('unsafe node: %s' % type(node).__name__) ast.NodeVisitor.visit(self, node) node_whitelist = [ 'Expression', 'Load', 'operator', 'unaryop', 'UnaryOp', 'BoolOp', 'BinOp', 'boolop', 'cmpop', # Operators 'Num', 'Str', 'List', 'Tuple', # Literals ] node_whitelist = [getattr(ast, name) for name in node_whitelist] checker = SafetyChecker(node_whitelist, ['a', 'b', 'foo', 'bar']) def safe_eval(expr, checker=checker): t = ast.parse(expr, 'test.py', 'eval') checker.visit(t) return eval(expr) Example: >>> safe_eval('2*a - bar') -4 >>> safe_eval('[1, 2] + [3, 4]') [1, 2, 3, 4] >>> safe_eval('f(foo)') Traceback (most recent call last): [...] __main__.UnsafeError: unsafe node: Call >>> safe_eval('x + 1') Traceback (most recent call last): [...] __main__.UnsafeError: unsafe name: x >>> safe_eval('lambda: x') Traceback (most recent call last): [...] __main__.UnsafeError: unsafe node: Lambda >>> safe_eval('foo or not foo') 'hello' You'd have to tweak the node_whitelist using the info at http://docs.python.org/library/ast.html#abstract-grammar -- Arnaud -- http://mail.python.org/mailman/listinfo/python-list