tags:

views:

132

answers:

2

Hi folks,

this is probably too simple of a question, but here I go.

I have paginated items, each page contains 100 items. The program fetches items till it reaches the item index specified within item_num

This is what I have:

item_num = 56

range(0, item_num/100 + (item_num%100 > 0)):
  get_next_100()

I'm not really sure about the (item_num%100 > 0) boolean I used.

Is there anything wrong with what I did?

+6  A: 

You seem to be trying to call the function zero times if item_num is 0, once if item_num is 1 to 100, twice if item_num is between 101 and 200, etc...

A simpler way to write this is:

n = 0
while n < item_num:
   get_next_100()
   n += 100

Or you could do it as a for loop:

for _ in range(0, item_num, 100):
   get_next_100()
Mark Byers
you might also consider `xrange` if you are using python version < 3.0
tgray
@Mark: hey Mark. Thanks for your answer! I'm using 1-based numbering btw.
RadiantHex
@Radiant: Ah yep, it seemed that you were trying to do something more complicated.
Mark Byers
+4  A: 

range takes a 3rd optional parameter of step.

So

range(0,234,100)

Gives

[0, 100, 200]

So you can do something like

for items in range(0,234,100):
    get_next_100()
Robert Christie
@cb160: actually... this is indeed the perfect answer!
RadiantHex
as I commented on Mark Byers answer, you might also consider `xrange` if you are using python version < 3.0
tgray