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
  Confused about python execution jpezz 4 443 Oct-09-2022, 06:56 PM
Last Post: Gribouillis
  Replicate Excel operations with Python Lumberjack 3 912 May-10-2022, 01:44 AM
Last Post: Lumberjack
  confused about string formatting barryjo 7 1,002 Mar-06-2022, 02:03 AM
Last Post: snippsat
  Pandas confused DPaul 6 1,535 Sep-19-2021, 06:45 AM
Last Post: DPaul
  is and '==' i'm confused hshivaraj 6 1,785 Sep-15-2021, 09:45 AM
Last Post: snippsat
  Program demonstrates operations of bitwise operators without using bitwise operations ShawnYang 2 1,207 Aug-18-2021, 03:06 PM
Last Post: deanhystad
  Confused with 'flags' tester_V 10 3,285 Apr-12-2021, 03:03 AM
Last Post: tester_V
  Simple Tic Tac Toe but I'm confused Izith 1 1,613 Sep-26-2020, 04:42 PM
Last Post: Larz60+
  I am really confused with this error. Runar 3 2,000 Sep-14-2020, 09:27 AM
Last Post: buran
  Random Choice Operations Souls99 6 2,003 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