Mr malik
Mr malik

Reputation: 31

BODMAS - python

I thought I understood BODMAS (BIDMAS in the UK). I'm unsure why the following expression evaluates in a different order:

a = 8*4//3

I expected 'division' to take place first, giving a = 8*1 - instead 'multiplication' occurs first, giving a = 32//3 = 10

b = 9//3*7

Example b evaluates to 21, as per BIDMAS rule.

It seems that python executes an expression from left to right and treats 'division' and 'multiplication' as equivalent. What's happening? Thanks in advance, Faz.

Upvotes: 3

Views: 23890

Answers (4)

Srini_N
Srini_N

Reputation: 1

My 1C here:

This is the formula for order of precedence:

  1. () : Parenthesis First!
  2. ** : Exponentiation
  3. *, @, /, //, % : all same precedence L to R
  4. +, - : all same precedence L to R

Example: problem under question: 8//3*3/2+10%2**2 ; This is solved in steps below using above formula.

  1. print(8//3*3/2+10%2**2)
  2. print(8//3*3/2+10%4) # Exponentiation applied (2 above)
  3. print(2*3/2+10%4) # (3 above)
  4. print(2*3/2+10%4) # (3 above)
  5. print(6/2+10%4) # (3 above)
  6. print(3+10%4) # (3 above)
  7. print(3+2) # (4 above)

#5.0 Final answer

List

Upvotes: 0

Mark
Mark

Reputation: 2311

Turning the comments on the OP into an independent answer, as this post shows up at the top of search results:

Multiplication & Division have equal precedence in Python, as well as according to the BODMAS/BEDMAS/BIDMAS/BIMDAS/BOMDAS/PEDMAS rule, so the evaluation then proceeds from Left to Right Python2 docs

Upvotes: 1

Drew
Drew

Reputation: 11

If you do a multiplication and a division it doesn't matter which order you do it in for example 6*5/3 = 10 the same as 6/3*5 = 10. The difference comes with addition where 6+3*5 = 21 but (6+3)*5 = 45.

Upvotes: 1

Oka
Oka

Reputation: 26355

In BEDMAS, BIDMAS, BOMDAS, BODMAS, PEDMAS, and other order of operations acronyms, division and multiplication carry the same weight and are calculated from left to right within their current block.

Read this section for clarification.

Upvotes: 3

Related Questions