[Tutor] ....and another thing!

dman dsh8290@rit.edu
Fri, 3 Aug 2001 11:40:01 -0400


On Fri, Aug 03, 2001 at 10:17:39AM -0700, kromag@nsacom.net wrote:

| 	total_cards=len(schmack)
| 	choose=random.randint(1,string.atoi(`total_cards`))
                                ^^^^^^^^^^^^^^^^^^^^^^^^^^
Why convert the integer to a string, then parse the string back to an
integer?

Also, as I look at
    http://python.mirrors.netnumina.com/doc/current/lib/module-random.html#l2h-875

I see that randint can return a number that is equal to the lower or
upper bounds.  You are using that number as the index in the next
line.

| 	chosen=schmack[choose] 

 
| I will get the occasional:
| 
| Traceback (most recent call last):
|   File "reader.py", line 9, in ?
|     chosen=schmack[choose] 
| IndexError: list index out of range
| >Exit code: 1

| should recalculate the number of items in the list with each iteration of the 
| loop. Since there are 72 items in the list, and one item is removed from the 
| list at the end of every iteration, it stands to reason that the list index 
| should be accurately recalculated by len(). Where am I going wrong?

If 'l' is a list,

    l[ len( l ) ] 

will try to access the element just past the end of the list.  For
your line above you want :

 	choose = random.randint( 0 , total_cards-1 )

and it will work.  By lowering the lower bound I am allowing the first
card to be chosen as well.

HTH,
-D