Python Forum
modulo and order of operations
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
modulo and order of operations
#1
I'm using 2.7.X
Working with the following:
print 100 - 25 * 3 % 4
When i run this i get 97 as the answer.

It seems like it I should be getting 6 with a 1 as remainder
-25 * 3 = -75
then 100-75 = 25
then 25/4=6 with 1 remainder

What is it that I'm missing in understanding this? Is there a page on the forum I have missed in my search that will explain this?
Thank you for any assistance
Reply
#2
25 * 3 = 75
75 % 4 = 3
100 - 3 = 97

Modulo has the same rank as * and /, so those operations are executed from left to right. And + or - go after them.
Reply
#3
This page shows the precedence of all operations:
https://docs.python.org/2/reference/expr...precedence

Multiplication and modulo have the same precedence, so they are done in the order they are listed.
Subtraction of course has lower precedence so it is done last.
>>> 25 * 3
75
>>> 75 % 4
3
>>> 100 - 3
97
>>> 25 * 3 % 4
3
>>> 100 - 25 * 3 % 4
97
Reply
#4
Awesome, Thank you. Big Grin
Knowing the order solves the issue
Reply
#5
When there's so many things going on, you should probably either use parentheses, or split the operation over several lines. For those of us who don't have any desire to remember that modulus is the same order of precedence as division.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Replicate Excel operations with Python Lumberjack 3 1,772 May-10-2022, 01:44 AM
Last Post: Lumberjack
  Program demonstrates operations of bitwise operators without using bitwise operations ShawnYang 2 1,757 Aug-18-2021, 03:06 PM
Last Post: deanhystad
  Random Choice Operations Souls99 6 2,889 Jul-31-2020, 10:37 PM
Last Post: Souls99
  Create bot to automate operations in IQ Option JonatasCavalini 0 12,267 Jul-19-2020, 02:23 AM
Last Post: JonatasCavalini
  Two operations in two ranges salwa17 3 2,092 Jun-22-2020, 04:15 PM
Last Post: perfringo
  How to avoid slow cursor operations? sevensixtwo 0 1,826 Oct-11-2019, 02:23 PM
Last Post: sevensixtwo
  Operations on indexed variables in loop Fibulavie 1 1,897 Aug-14-2019, 06:07 AM
Last Post: fishhook
  Confused by order of operations ward 4 2,589 Jan-22-2019, 08:53 PM
Last Post: Larz60+
  Confused by this modulo equation VikramSuh 3 3,167 Sep-05-2018, 12:43 PM
Last Post: VikramSuh
  Beginner user: mathematical operations Mahdi1994 1 2,815 Mar-19-2018, 11:07 AM
Last Post: Larz60+

Forum Jump:

User Panel Messages

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