[N00B] What's %?

Jeff Shannon jeff at ccvcorp.com
Thu Feb 10 18:40:53 EST 2005


Harlin wrote:

> What good is the modulus operator? What would I ever need it for?
> 
> * A quick way of testing whether an integer is even and odd
> * For that matter, a quick way of testing whether a the variable is a
> factor of any other arbitrary number.
> * In some programs (a weight control program I worked on comes to mind)
> it's necessary to get a remainder so that you can get the results of a
> leftover evenly divisible number.

Also, it's a good way to ensure that some number is in a specified 
range, and "wraps around" to the beginning if it goes out of that 
range.  For a quick & cheesy example, let's say we want to count time 
for music:

import time
def beats = ['one', 'two', 'three', 'four']

n = 0
while True:
     print beats[n]
     n = (n+1) % 4
     time.sleep(0.5)

By using '% 4', I ensure that n is always in the interval [0...4) 
(including 0 but not including 4).

Modulus is useful for all sorts of periodic behavior.

Jeff Shannon
Technician/Programmer
Credit International




More information about the Python-list mailing list