What is the result of % in Python?
Somewhat off topic, the %
is also used in string formatting operations like %=
to substitute values into a string:
>>> x = 'abc_%(key)s_'
>>> x %= {'key':'value'}
>>> x
'abc_value_'
Again, off topic, but it seems to be a little documented feature which took me awhile to track down, and I thought it was related to Pythons modulo calculation for which this SO page ranks highly.
The % (modulo) operator yields the remainder from the division of the first argument by the second. The numeric arguments are first converted to a common type. A zero right argument raises the ZeroDivisionError exception. The arguments may be floating point numbers, e.g., 3.14%0.7 equals 0.34 (since 3.14 equals 4*0.7 + 0.34.) The modulo operator always yields a result with the same sign as its second operand (or zero); the absolute value of the result is strictly smaller than the absolute value of the second operand [2].
Taken from http://docs.python.org/reference/expressions.html
Example 1:
6%2
evaluates to 0
because there's no remainder if 6 is divided by 2 ( 3 times ).
Example 2: 7%2
evaluates to 1
because there's a remainder of 1
when 7 is divided by 2 ( 3 times ).
So to summarise that, it returns the remainder of a division operation, or 0
if there is no remainder. So 6%2
means find the remainder of 6 divided by 2.