简体   繁体   中英

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.

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

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. +, -

Python gives multiplication and division the same priority.

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

  • 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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM