-8

What does the percentage

%

function do in python in a line such as

x % 2

user3222827
  • 5
  • 1
  • 1
  • 3

2 Answers2

4

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.

Prashant Kumar
  • 20,069
  • 14
  • 47
  • 63
2

This is called the modulus operator, it gives you the remainder after division:

>>> 5 % 2
1
>>> 44 % 3
2
>>> 
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199