Operators and Operations

In the last unit, we introduced some examples that contained operators and operations.

2 + 2 is referred to as an expression, which is the most basic kind of programming instructions in the language. Expressions consist of values (such as 2) and operators (such as +), and they always evaluate down to a single value. 2 + 2 evaluates to 4. A single value with no operators is also considered an expression, though it evaluates to itself:

>>> 2
2

Math operators from highest to lowest Precedence:

Operation Operator Example
Exponent ** 2 ** 3 -> 8
Modulus/remainder % 22 % 8 -> 6
Integer divison/floored quotient // 22 // 8 -> 2
Division / 22/8 -> 2.75
Multiplication * 5 * 3 -> 15
Subtraction - 5 - 3 -> 2
Addition + 2 + 4 -> 6

The order of operations (also called precedence) is similar to that of Mathematics. The * operator is evaluated first; the , /, //, and % operators are evaluated next, from left to right; and the + and - operators are evaluated last (also from left to right). You can use parentheses to override the usual precedence if you need to. For example:

>>> 2 + 3 * 6
20

>>> (2 + 3) * 6
30

>>> 48565878 * 578453
28093077826734

>>> 2 ** 8
256

>>> 23 / 7
3.2857142857142856

>>> 23 // 7
3

>>> 23 % 7
2

>>> (5 - 1) * ((7 + 1) / (3 - 1))
16.0

These rules for putting operators and values together to form expressions are a fundamental part of Python as a programming language, just like the grammar rules that help us communicate. Here’s an example:

  • This is a grammatically correct English sentence.
  • This grammatically sentence is not English a correct.

The second line is difficult to understand because it doesn’t follow the rules of English. Similarly, if you type in a bad Python instruction, Python won’t be able to understand it and will display a SyntaxError error message, as shown here:

>>> 4 +
  File "<stdin>", line 1
    4 +
      ^
SyntaxError: invalid syntax

>>> 2 + 5 + * 2
  File "<stdin>", line 1
    2 + 5 + * 2
            ^
SyntaxError: invalid syntax

To test an instruction, simply type it in the Repl interactive shell. It is not necessary that every line of code you write will be correct. Don't worry, you won't break your computer! The worst thing that could happen is that Python responds with an error message.

Questions:

  1. Which of these are operators? (Multiple options) a. 'hello' b. / c. * d. 4.0

  2. Which of these are values? (Multiple options) a. 'hello' b. / c. * d. 4.0

results matching ""

    No results matching ""