[N00B] What's %?

Delaney, Timothy C (Timothy) tdelaney at avaya.com
Thu Feb 10 18:13:46 EST 2005


Harlin wrote:

> In the mode of anticipating another question... I get these all the
> time at work of all places! You'd think IT workers would know the
> answer to these...
> 
> What good is the modulus operator? What would I ever need it for?

# Print a summary every 100 rows
for i in range(1, 1001):
    if i % 100 == 0:
        print 'Summary: %s rows' % (i,)

There are two examples of using the modulo operator in the above - one
is using it in it's intended integer form, and the other is using it in
its overloaded string formatting form.

Note that the range is from 1 (inclusive) to 1001 (exclusive). If you
used the normal range(1000) you would get a summary on the first time
round the loop, and wouldn't get one for the last 99. Why is for you to
work out ;)

Tim Delaney



More information about the Python-list mailing list