-1

Can anybody explain me the following code. I did not understand what % does. As I know it returns remainder, but I did not get the output i was expecting. What is remainder itself? can you please explain output step by step.

for num in range(20):
    if num % 4 == 0:
        print num 
    if num % 16 == 0:
        print('XYZ')
nbrooks
  • 18,126
  • 5
  • 54
  • 66
Jamol
  • 3,768
  • 8
  • 45
  • 68

3 Answers3

6

That operator is called the modulus operator, and what it does is, basically, continues subtracting the right hand side from the left hand side until it can't go any more (So, subtracting again would make the result negative). The number that's left at the point it cannot subtract anymore is called the remainder.

It's like doing division, but throwing away the quotient.

Try running the code:

 for i in xrange(10):
      print str(i) + " : " + str((i % 2))

See the pattern?

alvonellos
  • 1,009
  • 1
  • 9
  • 27
2

% is called modulus operator & is used to get the remainder.

num % 4 == 0 simply checks if num is divisible by 4

loxxy
  • 12,990
  • 2
  • 25
  • 56
0

mod, modulous, remainder http://docs.python.org/library/operator.html

Matt
  • 68,711
  • 7
  • 155
  • 158