7

Possible Duplicate:
How do you check whether a number is divisible by another number (Python)?

so I'm writing up a "stopwatch game" in python for a course I'm doing, and I want it so that when the timer stops on a whole number, the player receives a point.

I figure that a "whole number" will be a multiple of 10, as the format would be something like this a;bc:d, and the timer is running at a tenth of a second.

What I need your help for is how would I go about saying, "Oh hey, if he stops on a multiple of 10, give him a point".

I cannot for the life of me figure out how to put specify a multiple of 10.

Community
  • 1
  • 1
Matthew Westley
  • 89
  • 1
  • 1
  • 2

3 Answers3

17

Use the % (modulo operation). Eg:

>>> 100%10
0
>>> 101%10
1

Basically, x%y returns the value of the remainder of x/y, so if the remainder is 0, than x is evenly divisible by y. Therefore, if x%10 returns something other than a zero, x is not divisible by 10.

Matthew Adams
  • 9,426
  • 3
  • 27
  • 43
4

You should try using a modulo in your script.

See :

>>> if not 10 % 10:
...     print "OK"
... 
OK
>>> if not 9 % 10:
...     print "OK"
... 
>>> 
Gilles Quénot
  • 173,512
  • 41
  • 224
  • 223
2

If a number is a multiple of 10, the remainder when you divide it by 10 will be 0. You can get the remainder of a division in Python by using the % operator. For example:

print 13 % 10  # 3

This is a slight oversimplification; % (modulus/modulo) is different than remainder for negative operands.

icktoofay
  • 126,289
  • 21
  • 250
  • 231