As you can see, dividing 3/7 yields a fraction. But when I do 3%7 it yields 3. How could this be? I suppose I expected an output value of 4 (because it would take 4 to complete 7) or 0, (because there is no remainder at all if you use integer division such as 3//7).
>>> 3/7
0.42857142857142855
>>> 3%7
3
>>>
Just trying to understand the depths of Python. Thanks!
Remember long division? Before you learned about fractions, 50 divided by 7
would be 7, remainder 1
. The remainder
is the modulus. It is the numerator of the 1/7
remaining after integer division.
Let's use different numbers for demonstration.
42 divided by 5 gives a quotient of 8 and a remainder of 2. That means 42 // 5 == 8
and 42 % 5 == 2
.
3 divided by 7 gives a quotient of 0 and a remainder of 3. That means 3 // 7 == 0
and 3 % 7 == 3
.
In Python, //
and %
represent the quotient and remainder you probably learned about before you learned about fractions and real numbers. The only (possible) difference is that //
floors and %
matches the sign of the right-hand operand.
modulo returns the whole number after integer (floor) division.
>>>3//7
0 # with remainder 3
>>>3%7
3
>>>2//5
2 # with remainder 1
>>>2%5
1
Re-reading your question, it occurred to me you got your terms mixed up and that may have been the underlying confusion that none of us properly answered.
But when I do 3%7 it yields 3. How could this be? I suppose I expected an output value of 4 (because it would take 4 to complete 7)
So first that issue was masked when you said 4. Since 4 is greater than 3, 3 can be subtracted a second time, leaving 1. So 1
is the output of 7 % 3
.
But you asked about 3 % 7
, even though you then proceeded to explain 7 % 3
. 3 % 7
is less than 1 (because 7 > 3). So that is why the modulus is still 3. Integer division gives you 0, so 3 is left.
Take the first term (3) divided by the second term (7) using integer division (resulting in 0). Subtract that number from the first term (3) and you get 3. So: 3 % 7 = 3
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.