Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python Mathematical Order of Operation

please can someone explain to me why the expression 2 + 4 / 2 * 3 evaluates to 8.0 and not 2.66?

I thought that multiplication was performed before division, however in this instance it seems that the division operation is being performed before the multiplication.

like image 467
Zogrod Avatar asked Dec 22 '25 14:12

Zogrod


1 Answers

Because it's evaluated as:

2 + ((4 / 2) * 3)

Because * and / have higher precedence than + and it's left to right when the operators have the same precedence.

Quoting from the docs:

The following table summarizes the operator precedence in Python, from lowest precedence (least binding) to highest precedence (most binding). Operators in the same box have the same precedence. Unless the syntax is explicitly given, operators are binary. Operators in the same box group left to right (except for exponentiation, which groups from right to left).

Operator Description

  • [...]
  • +, - Addition and subtraction
  • *, @, /, //, % Multiplication, matrix multiplication, division, floor division, remainder
  • [...]
like image 111
MSeifert Avatar answered Dec 24 '25 02:12

MSeifert