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
  String int confused janeik 7 1,017 Aug-02-2023, 01:26 AM
Last Post: deanhystad
  I am confused with the key and value thing james1019 3 912 Feb-22-2023, 10:43 PM
Last Post: deanhystad
  Replicate Excel operations with Python Lumberjack 3 1,772 May-10-2022, 01:44 AM
Last Post: Lumberjack
  Pandas confused DPaul 6 2,468 Sep-19-2021, 06:45 AM
Last Post: DPaul
  is and '==' i'm confused hshivaraj 6 2,626 Sep-15-2021, 09:45 AM
Last Post: snippsat
  Program demonstrates operations of bitwise operators without using bitwise operations ShawnYang 2 1,757 Aug-18-2021, 03:06 PM
Last Post: deanhystad
  Confused with 'flags' tester_V 10 4,788 Apr-12-2021, 03:03 AM
Last Post: tester_V
  Simple Tic Tac Toe but I'm confused Izith 1 2,154 Sep-26-2020, 04:42 PM
Last Post: Larz60+
  I am really confused with this error. Runar 3 2,927 Sep-14-2020, 09:27 AM
Last Post: buran
  Random Choice Operations Souls99 6 2,889 Jul-31-2020, 10:37 PM
Last Post: Souls99

Forum Jump:

User Panel Messages

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