r/learnpython • u/[deleted] • Sep 15 '24
What's the difference between % (modulo) and // (floor division)
Hello, Can someone please explain the me the difference between those two arithmetic signs because am new to programming python:)
8
Sep 15 '24
There's a function called divmod that does both, and if you use that a few times, you'll get a feel for the difference.
For example, let's say you have a quantity of money, and you want to make change.
cents = 93
quarters, cents = divmod(cents, 25)
dimes, cents = divmod(cents, 10)
nickels, cents = divmod(cents, 5)At each step, we take as many chunks as we can (that's the div), then we keep any leftovers (that's the mod)
7
u/MrPhungx Sep 15 '24
101 // 10 = 10101 % 10 = 1
The floor division is like "how often does the 10 fit into the 101". Or you can think about it as a regular division in combination with cutting off the decimal point.
Modulo on the other hand is "how often does the 10 fit into the 101 and give me what is left". The modulo operator returns the remainder of the division.
1
1
u/FrangoST Sep 15 '24
if you divide a number by another number, in a piece of paper, you usually divide it by parts, and eventually you'll get a remainder that is smaller than the number you want to divide it with... if you stop in this moment, and want the division result so far, you do "//" (floor division)... if you want the remainder, you do "%" (modulo)...
ie: 125/10 12/10 results in 1 and leaves 2 as remainder... then you put those 2 down, it becomes 20 as you add 5 to it and you get 25 25/10 is 2 and 5 as remainder... so the division result so far is 12 and 5 is left... to divide 5 by 10 you'd need to have a decimal number as a result, so you stop here and 12 is the floor division result (125//10), and the remainder 5 is the modulo result (125%10)
if you do the division on paper it becomes clear, otherwise it might be an issue of fundamental math comprehension.
1
u/Disastrous-Team-6431 Sep 16 '24
Nobody explaining that this has nothing to do with python whatsoever?
1
Sep 16 '24
You know when you have 5 pieces of cake and need to share it between 3 people?
// tells you that each person gets one piece and % tells you that there are two pieces left over.
5
u/jsavga Sep 15 '24 edited Sep 15 '24
% (modulo) gives you the Remainder
// (floor division) gives you the Quotient
https://i.postimg.cc/3RjxTQR9/Quotient-Remainder.png shows you the different parts of a division operation.
Now let's see some examples:
7 / 5 quotient = 1, remainder = 2
5 / 7 quotient = 0, remainder equals = 5 (this is harder to understand but it's correct)