Python Forum
Confused by order of operations
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Confused by order of operations
#1
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.)
Reply
#2
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.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
FYI Official doc: https://en.wikibooks.org/wiki/Python_Pro...Operations
Reply
#4
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
Reply
#5
I think we graduated high school same year, 1964 for me!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Pandas confused DPaul 6 196 Sep-19-2021, 06:45 AM
Last Post: DPaul
  is and '==' i'm confused hshivaraj 6 342 Sep-15-2021, 09:45 AM
Last Post: snippsat
  Program demonstrates operations of bitwise operators without using bitwise operations ShawnYang 2 214 Aug-18-2021, 03:06 PM
Last Post: deanhystad
  Confused with 'flags' tester_V 10 1,277 Apr-12-2021, 03:03 AM
Last Post: tester_V
  Simple Tic Tac Toe but I'm confused Izith 1 646 Sep-26-2020, 04:42 PM
Last Post: Larz60+
  I am really confused with this error. Runar 3 827 Sep-14-2020, 09:27 AM
Last Post: buran
  Random Choice Operations Souls99 6 946 Jul-31-2020, 10:37 PM
Last Post: Souls99
  Two operations in two ranges salwa17 3 779 Jun-22-2020, 04:15 PM
Last Post: perfringo
  Confused by 'break' in the official documents Chuck_Norwich 2 847 Apr-12-2020, 09:26 PM
Last Post: Chuck_Norwich
  Confused on how to go about writing this or doing this... pythonforumuser 3 969 Feb-10-2020, 09:15 AM
Last Post: snippsat

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020