What does the percentage
%
function do in python in a line such as
x % 2
In this context it is the modulus, or remainder in the math sense.
So 7 % 2 == 1
because when you divide 7 by 2, you get a remainder of 1.
Similarly, if you wanted the fact that 2 goes into 7 three times, 7 // 2 == 3
The context is important, because %
can also be used for old-style string formatting.
In that context, '%s to %s' % ('A', 'Z')
would return a string 'A to Z'
However, don't use %
for string formatting in python today. Use str.format
.
This is called the modulus operator, it gives you the remainder after division:
>>> 5 % 2
1
>>> 44 % 3
2
>>>