Computer Studies‎ > ‎Python‎ > ‎Python Tutorial‎ > ‎

Order of Operations

Remember from math class that 3 + 2 X 5 = 13, not 25. The same holds true for Python.

Even though Python will calculate algebraic equations properly, it is good programming practice to group items into their intended order of operation by surrounding them with parentheses (round brackets). For example, the above equation, written with a Python print statement, is better written as:

print (3 + (2 * 5))

A more complex equation may be written as:

print (12 + ( ( 4 - 6 ) / 3 ))

Things to remember:
  • Python uses '*' for multiplication, not 'x'
  • Python uses '**' for exponentiation
  • Python only uses parentheses (round brackets), not square brackets
  • Brackets can be nested (i.e., inside each other), and it is strongly encouraged if it makes the statement clearer
Assignment

Write a program that prints the equivalent of each of the following algebraic statements to the screen. Don't forget to use parentheses for clarity.

  • 2 + 4 x 5
  • 2 x 6 - 4/2
  • 8 + 2
  • (4+9/3)
  • 3[(4+12)-2(3-1)]
  • 23 + 42 - 6/3
For each output statement, copy and paste the above formulas exactly as shown, then append your calculated answer. For example, the 5th line would look something like this:

3[(4+12)-2(3-1)] = <your calculated answer here>

Save as "012.py".
Comments