Python Forum

Full Version: Confused by order of operations
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.)
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.
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
I think we graduated high school same year, 1964 for me!