Zogrod
Zogrod

Reputation: 31

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.

Upvotes: 2

Views: 5437

Answers (5)

kibromhft
kibromhft

Reputation: 1047

The order of python operations follows the same rules. You can remember it using the mnemonic " please excuse my dear aunt Sally." or PEMDAS when executing math. PEMDAS stands for Parenthesis, Exponentiation, Multiplication, Division, Addition, and Subtraction. However, Multiplication and division can have the same precedence but are differentiated by their orders from left to right. Addition and Subtraction also behave in the same way.

Upvotes: 1

user8660928
user8660928

Reputation: 19

Python gives multiplication and division the same priority.

As a rule, same priority operations are executed in order from left to right.

Upvotes: 2

Yes, division and multiplication is calculated first, but multiplication is´nt performed before division and vice versa. So: 2 + 4/2 * 3 = 2+2*3 = 2+6 = 8
1. ()
2. %, /, *
3. +, -

Upvotes: 2

Aditya Shrivastava
Aditya Shrivastava

Reputation: 55

  • Python basic operaters follow the BODMAS rule and due to accordance of that priority of division is higher than multiplication.So it goes this way: 2+(4/2)*3
  • Now if you want to get 2.66 as your answer it must be like 2+4/(2*3)

Upvotes: 0

MSeifert
MSeifert

Reputation: 152587

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
  • [...]

Upvotes: 8

Related Questions