Python Forum
Confused by order of operations - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Confused by order of operations (/thread-15574.html)



Confused by order of operations - ward - Jan-22-2019

I'm doing a seminar to learn Python, and I've been asked to predict the result of this code:
print ( 5*2 - 3+4/2 )
The lesson explained the order of operations as Parentheses, Exponents, Multiplication and Division, Addition and Subtraction. So I first multiplied 5 by 2 to get 10. Then I divided 4 by 2 to get 2. So now it's 10 - 3 + 2. Then I added 3 to 2 to get 5. Finally, I subtracted 5 from 10. So I predicted the result to be 5.

But here's the result:
Output:
9.0
. What's wrong with my calculation? What order of operations could result in 9.0? (I'm using Python 3.)


RE: Confused by order of operations - ichabod801 - Jan-22-2019

Addition and subtraction are at the same level (just like multiplication and division). Everything at the same level is done left to right, then move to the next level. So 10 - 3 first, then add 2 to that.


RE: Confused by order of operations - Larz60+ - Jan-22-2019

FYI Official doc: https://en.wikibooks.org/wiki/Python_Programming/Basic_Math#Order_of_Operations


RE: Confused by order of operations - ward - Jan-22-2019

Thanks for your answer, ichabod801. If I were to edit the tutorial, I'd have said "Parentheses,
Exponents, Multiplication/Division, Addition/Subtraction" to convey that the latter sequences are not strict; they depend on whichever operator is encountered first, from left to right.

And thanks for the link, Larz60+; it looks like a good resource.

In my defense, I learned about order of operations in high school 55 years ago, so it's a little foggy Wink


RE: Confused by order of operations - Larz60+ - Jan-22-2019

I think we graduated high school same year, 1964 for me!