|


Operator PrecedenceDate: 08/13/2003 at 15:47:44 From: Felix Subject: Operators and operands These questions are from the following web site: Variables, expressions and statements http://www.ibiblio.org/obp/thinkCSpy/chap02.htm It is from: How to Think Like a Computer Scientist Learning with Python by Allen B. Downey, Jeffrey Elkner and Chris Meyers Printed copies now available from Green Tea Press. I am attempting to understand Python and I have not ever programmed. " . . . order of operations: · Parentheses have the highest precedence and can be used to force an expression to evaluate in the order you want. Since expressions in parentheses are evaluated first, 2 * (3-1) is 4, and (1+1)**(5-2) is 8. You can also use parentheses to make an expression easier to read, as in (minute * 100) / 60, even though it doesn't change the result. · Exponentiation has the next highest precedence, so 2**1+1 is 3 and not 4, and 3*1**3 is 3 and not 27... " Since the following statement is true: (1+1)**(5-2) is 8. Why is the following statement true and not false: 2**1+1 is 3 and not 4, and 3*1**3 is 3 and not 27 ? Date: 08/13/2003 at 16:59:05 From: Doctor Peterson Subject: Re: Operators and operands Hi, Felix. This is essentially the same idea as what we call "order of operations" in math: Order of operations http://mathforum.org/dr.math/faq/faq.order.operations.html "Operator precedence" is a more sophisticated term for it. The main difference between what you see in a programming language and what we do in writing math is that exponents are indicated by the operator "**" (or by "^" in some other languages) rather than by writing a superscript, and that makes it a little less obvious what order should be used. The rule you have been given is that the exponentiation operator has the highest precedence; that means it must be done before other operations. So when we see 2**1+1 we have to evaluate it this way: 2**1+1 \__/ 2 +1 \__/ 3 If we meant to do the addition first, we would have to use parentheses: 2**(1+1) \___/ 2** 2 \____/ 4 If we were writing this in the usual mathematical way, the two expressions would look like 1 1+1 2 +1 and 2 and parentheses would not be needed to make the difference clear, since the location of the numbers shows how they are to be connected. The rule of precedence is still needed, though, for expressions like this: 3 1+2 which means 3 1 + (2 ) rather than 3 (1 + 2) In Python, these are 1+2**3 1+(2**3) (1+2)**3 and the first two, again, mean the same thing. If you have any further questions, feel free to write back. - Doctor Peterson, The Math Forum http://mathforum.org/dr.math/ |
Search the Dr. Math Library: |
[Privacy Policy] [Terms of Use]


Ask Dr. MathTM
© 1994-2013 The Math Forum
http://mathforum.org/dr.math/