07-operators-expressions.pd 8.7 KB

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