I tried to calculate the output of this problem in python: 4+6/2 and it was 7 then i reversed them as 6+4/2 and answer was 8. now whats the difference, and why this occurs? what is divided first?
Asked
Active
Viewed 505 times
-5
-
Those are different things in all programming languages that I've ever seen, and in math. Would you expect them to give the same answer if you did this with a pencil and paper? – ChrisGPT was on strike Jul 01 '20 at 15:40
-
See [Precedence of Python operations](https://www.programiz.com/python-programming/precedence-associativity) – DarrylG Jul 01 '20 at 15:41
-
Sounds like you expected `(4+6)/2` vs `(6+4)/2`, which are both 5 – OneCricketeer Jul 01 '20 at 15:49
1 Answers
1
Python uses PEMDAS, as do most languages. Division comes before addition, so it would be calculated as 4+(6/2)=4+3=7, and 6+(4/2)=8. This can be confirmed with any calculator.
PEMDAS is the standard order of operations:
P- Parentheses first
E- Exponents second
M/D- Multiplication or Division third (If there are multiple multiplication or division signs in a row, then operate first to last)
A/S- Addition or Subtraction fourth (If there are multiple addition or subtraction signs in a row, then operate first to last)

iceblizzard
- 21
- 3
-
3An explanation of what `PEMDAS` means would improve this answer greatly. – Mark Ransom Jul 01 '20 at 15:46
-
-
thank you very much but i still have one more question:as you said, if we try to calculate this:4+6/2, python first will calculate the outcome of 6/2 then +4, why doesn't it first calculate this 4/2 then + 6? – Clark Jul 02 '20 at 11:46
-
-
I got it, I calculated it using a calculator and the answer was just as you said.THANK YOU VERY MUCH. – Clark Jul 03 '20 at 18:00