op_exp.asciidoc 9.2 KB

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