Python Forum
Confused by this modulo equation
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Confused by this modulo equation
#1
This is probably a simple question for experienced users...I'm just starting with Python and I'm working with modulo equations. The tutorial I'm using had this equation: (100 - 25 * 3 % 4), and the result is 97. How to explain that? As I understand it, we take the first part of the equation first, so (100 - 25 * 3). When I run that by itself I get 25. And (25 % 4) results in 1. So where do they get 97?
Reply
#2
modulo operator has the same priority as division
Output:
In [47]: 25 * 3 % 4 Out[47]: 3
The result is right.

If it is unclear - the evaluation order is
100 - ((25 * 3) % 4)
Test everything in a Python shell (iPython, Azure Notebook, etc.)
  • Someone gave you an advice you liked? Test it - maybe the advice was actually bad.
  • Someone gave you an advice you think is bad? Test it before arguing - maybe it was good.
  • You posted a claim that something you did not test works? Be prepared to eat your hat.
Reply
#3
Every language has a operator-precedence.
The most manuals shows the order from high priority to low priority. It's reversed in Pythons documentation.

When operators do have the same precedence, they are evaluated from left to right.
My code examples are always for Python >=3.6.0
Almost dead, but too lazy to die: https://sourceserver.info
All humans together. We don't need politicians!
Reply
#4
Okay, I finally understand, I had the operator precedence wrong. So 25*3 = 75, then we do 75 % 4 = 3, THEN we finally subtract 3 from 100, to get 97. I'll have to practice, ha ha.

Thanks for the help!
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
  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 644 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
  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
  I always get 'None' returned. Confused. What did I miss? jpezz 2 1,079 Apr-07-2019, 10:06 AM
Last Post: jpezz
  Confused by order of operations ward 4 1,255 Jan-22-2019, 08:53 PM
Last Post: Larz60+
  I am new to python , i am confused with this syntax , please help aankrose 3 1,409 Aug-03-2018, 06:49 PM
Last Post: aankrose

Forum Jump:

User Panel Messages

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