op_exp.asciidoc 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  1. [[op_exp]]
  2. == Operators and Expressions
  3. Most statements (logical lines) that you write will contain _expressions_. A simple example of an
  4. expression is `2 + 3`. An expression can be broken down into operators and operands.
  5. _Operators_ are functionality that do something and can be represented by symbols such as `+` or by
  6. special keywords. Operators require some data to operate on and such data is called _operands_. In
  7. this case, `2` and `3` are the operands.
  8. === Operators
  9. We will briefly take a look at the operators and their usage.
  10. Note that you can evaluate the expressions given in the examples using the interpreter
  11. interactively. For example, to test the expression `2 + 3`, use the interactive Python interpreter
  12. prompt:
  13. [source,python]
  14. --------------------------------------------------
  15. >>> 2 + 3
  16. 5
  17. >>> 3 * 5
  18. 15
  19. >>>
  20. --------------------------------------------------
  21. Here is a quick overview of the available operators:
  22. `+` (plus) ::
  23. Adds two objects
  24. +
  25. `3 + 5` gives `8`. `'a' + 'b'` gives `'ab'`.
  26. `-` (minus) ::
  27. Gives the subtraction of one number from the other; if the first operand is absent it is assumed to
  28. be zero.
  29. +
  30. `-5.2` gives a negative number and `50 - 24` gives `26`.
  31. ++*++ (multiply) ::
  32. Gives the multiplication of the two numbers or returns the string repeated that many times.
  33. +
  34. `2 * 3` gives `6`. `'la' * 3` gives `'lalala'`.
  35. ++**++ (power) ::
  36. Returns x to the power of y
  37. +
  38. `3 ** 4` gives `81` (i.e. `3 * 3 * 3 * 3`)
  39. `/` (divide) ::
  40. Divide x by y
  41. +
  42. `13 / 3` gives `4`.
  43. `13.0 / 3` gives `4.333333333333333`
  44. `%` (modulo) ::
  45. Returns the remainder of the division
  46. +
  47. `13 % 3` gives `1`. `-25.5 % 2.25` gives `1.5`.
  48. `<<` (left shift) ::
  49. Shifts the bits of the number to the left by the number of bits specified. (Each number is
  50. represented in memory by bits or binary digits i.e. 0 and 1)
  51. +
  52. `2 << 2` gives `8`. `2` is represented by `10` in bits.
  53. +
  54. Left shifting by 2 bits gives `1000` which represents the decimal `8`.
  55. `>>` (right shift) ::
  56. Shifts the bits of the number to the right by the number of bits specified.
  57. +
  58. `11 >> 1` gives `5`.
  59. +
  60. `11` is represented in bits by `1011` which when right shifted by 1 bit gives `101`which is the
  61. decimal `5`.
  62. `&` (bit-wise AND) ::
  63. Bit-wise AND of the numbers
  64. +
  65. `5 & 3` gives `1`.
  66. `|` (bit-wise OR) ::
  67. Bitwise OR of the numbers
  68. +
  69. `5 | 3` gives `7`
  70. `^` (bit-wise XOR) ::
  71. Bitwise XOR of the numbers
  72. +
  73. `5 ^ 3` gives `6`
  74. `~` (bit-wise invert) ::
  75. The bit-wise inversion of x is -(x+1)
  76. +
  77. `~5` gives `-6`. More details at http://stackoverflow.com/a/11810203
  78. `<` (less than) ::
  79. Returns whether x is less than y. All comparison operators return `True` or `False`. Note the
  80. capitalization of these names.
  81. +
  82. `5 &lt; 3` gives `False` and `3 &lt; 5` gives `True`.
  83. +
  84. Comparisons can be chained arbitrarily: `3 < 5 < 7` gives `True`.
  85. `>` (greater than) ::
  86. Returns whether x is greater than y
  87. +
  88. `5 > 3` returns `True`. If both operands are numbers, they are first converted to a common
  89. type. Otherwise, it always returns `False`.
  90. `<=` (less than or equal to) ::
  91. Returns whether x is less than or equal to y
  92. +
  93. `x = 3; y = 6; x <= y` returns `True`.
  94. `>=` (greater than or equal to) ::
  95. Returns whether x is greater than or equal to y
  96. +
  97. `x = 4; y = 3; x >= 3` returns `True`.
  98. `==` (equal to) ::
  99. Compares if the objects are equal
  100. +
  101. `x = 2; y = 2; x == y` returns `True`.
  102. +
  103. `x = 'str'; y = 'stR'; x == y` returns `False`.
  104. +
  105. `x = 'str'; y = 'str'; x == y` returns `True`.
  106. `!=` (not equal to) ::
  107. Compares if the objects are not equal
  108. +
  109. `x = 2; y = 3; x != y` returns `True`.
  110. `not` (boolean NOT) ::
  111. If x is `True`, it returns `False`. If x is `False`, it returns `True`.
  112. +
  113. `x = True; not x` returns `False`.
  114. `and` (boolean AND) ::
  115. `x and y` returns `False` if x is `False`, else it returns evaluation of y
  116. +
  117. `x = False; y = True; x and y` returns `False` since x is False. In this case, Python will not
  118. evaluate y since it knows that the left hand side of the 'and' expression is `False` which implies
  119. that the whole expression will be `False` irrespective of the other values. This is called
  120. short-circuit evaluation.
  121. `or` (boolean OR) ::
  122. If x is `True`, it returns True, else it returns evaluation of y
  123. +
  124. `x = True; y = False; x or y` returns `True`. Short-circuit evaluation applies here as well.
  125. === Shortcut for math operation and assignment
  126. It is common to run a math operation on a variable and then assign the result of the operation back
  127. to the variable, hence there is a shortcut for such expressions:
  128. [source,python]
  129. --------------------------------------------------
  130. a = 2
  131. a = a * 3
  132. --------------------------------------------------
  133. can be written as:
  134. [source,python]
  135. --------------------------------------------------
  136. a = 2
  137. a *= 3
  138. --------------------------------------------------
  139. Notice that `var = var operation expression` becomes `var operation= expression`.
  140. === Evaluation Order
  141. If you had an expression such as `2 + 3 * 4`, is the addition done first or the multiplication? Our
  142. high school maths tells us that the multiplication should be done first. This means that the
  143. multiplication operator has higher precedence than the addition operator.
  144. The following table gives the precedence table for Python, from the lowest precedence (least
  145. binding) to the highest precedence (most binding). This means that in a given expression, Python
  146. will first evaluate the operators and expressions lower in the table before the ones listed higher
  147. in the table.
  148. The following table, taken from the
  149. http://docs.python.org/3/reference/expressions.html#operator-precedence[Python reference manual],
  150. is provided for the sake of completeness. It is far better to use parentheses to group operators
  151. and operands appropriately in order to explicitly specify the precedence. This makes the program
  152. more readable. See <<changing_order_of_evaluation,Changing the Order of Evaluation>> below for
  153. details.
  154. `lambda` :: Lambda Expression
  155. `if - else` :: Conditional expression
  156. `or` :: Boolean OR
  157. `and` :: Boolean AND
  158. `not x` :: Boolean NOT
  159. `in, not in, is, is not, <, <=, >, >=, !=, ==` :: Comparisons, including membership tests and identity tests
  160. `|` :: Bitwise OR
  161. `^` :: Bitwise XOR
  162. `&` :: Bitwise AND
  163. `<<, >>` :: Shifts
  164. `+, -` :: Addition and subtraction
  165. `*, /, //, %` :: Multiplication, Division, Floor Division and Remainder
  166. `+x, -x, ~x` :: Positive, Negative, bitwise NOT
  167. `**` :: Exponentiation
  168. `x[index], x[index:index], x(arguments...), x.attribute` :: Subscription, slicing, call, attribute reference
  169. `(expressions...), [expressions...], {key: value...}, {expressions...}` :: Binding or tuple display, list display, dictionary display, set display
  170. The operators which we have not already come across will be explained in later chapters.
  171. Operators with the _same precedence_ are listed in the same row in the above table. For example,
  172. `+` and `-` have the same precedence.
  173. [[changing_order_of_evaluation]]
  174. === Changing the Order Of Evaluation
  175. To make the expressions more readable, we can use parentheses. For example, `2 + (3 * 4)` is
  176. definitely easier to understand than `2 + 3 * 4` which requires knowledge of the operator
  177. precedences. As with everything else, the parentheses should be used reasonably (do not overdo it)
  178. and should not be redundant, as in `(2 + (3 * 4))`.
  179. There is an additional advantage to using parentheses - it helps us to change the order of
  180. evaluation. For example, if you want addition to be evaluated before multiplication in an
  181. expression, then you can write something like `(2 + 3) * 4`.
  182. === Associativity
  183. Operators are usually associated from left to right. This means that operators with the same
  184. precedence are evaluated in a left to right manner. For example, `2 + 3 + 4` is evaluated as `(2 +
  185. 3) + 4`. Some operators like assignment operators have right to left associativity i.e. `a = b = c`
  186. is treated as `a = (b = c)`.
  187. === Expressions
  188. Example (save as +expression.py+):
  189. [source,python]
  190. --------------------------------------------------
  191. length = 5
  192. breadth = 2
  193. area = length * breadth
  194. print 'Area is', area
  195. print 'Perimeter is', 2 * (length + breadth)
  196. --------------------------------------------------
  197. Output:
  198. --------------------------------------------------
  199. $ python expression.py
  200. Area is 10
  201. Perimeter is 14
  202. --------------------------------------------------
  203. .How It Works
  204. The length and breadth of the rectangle are stored in variables by the same name. We use these to
  205. calculate the area and perimeter of the rectangle with the help of expressions. We store the result
  206. of the expression `length * breadth` in the variable +area+ and then print it using the +print+
  207. function. In the second case, we directly use the value of the expression `2 * (length + breadth)`
  208. in the print statement.
  209. Also, notice how Python _pretty-prints_ the output. Even though we have not specified a space
  210. between `'Area is'` and the variable `area`, Python puts it for us so that we get a clean nice
  211. output and the program is much more readable this way (since we don't need to worry about spacing
  212. in the strings we use for output). This is an example of how Python makes life easy for the
  213. programmer.
  214. === Summary
  215. We have seen how to use operators, operands and expressions - these are the basic building blocks
  216. of any program. Next, we will see how to make use of these in our programs using statements.