random - Python - empty range for randrange() (0,0, 0) and ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width)) -
when run program: (python 3.3.1)
import random import time random import randrange print(' ') print('i thinking of person...') time.sleep(1) print('he or belongs group of people:') people = 'alice elise jack jill ricardo david jane sacha thomas'.split() loop = 0 while loop != 6: group = [] person = randrange(0, len(people)) personname = people[person] int(person) group.append(personname) del people[person] loop = loop + 1
i error message:
traceback (most recent call last): file "c:\users\user\python\wsda.py", line 132, in <module> person = randrange(0, len(people)) file "c:\python33\lib\random.py", line 192, in randrange raise valueerror("empty range randrange() (%d,%d, %d)" % (istart, istop, width)) valueerror: empty range randrange() (0,0, 0)
basically want 6 random names variable 'people' , add variable 'group'...
also part of larger program based on guess game... please tell me how fix this? thx
the error occurs when people
list empty (length 0). may want test that:
>>> import random >>> random.randrange(0, 0) traceback (most recent call last): file "<stdin>", line 1, in <module> file "/users/mj/development/libraries/buildout.python/parts/opt/lib/python2.7/random.py", line 217, in randrange raise valueerror, "empty range randrange() (%d,%d, %d)" % (istart, istop, width) valueerror: empty range randrange() (0,0, 0)
if need add 6 random choices people
list better shuffle people
list , add first 6 of list group
:
import random people = 'alice elise jack jill ricardo david jane sacha thomas'.split() random.shuffle(people) group.extend(people[:6]) people = people[6:] # remainder, 6 picks have been removed
but chances of course end empty list again @ point.
another approach use random.sample()
:
people = 'alice elise jack jill ricardo david jane sacha thomas'.split() group.extend(random.sample(people, 6))
this picks 6 random names list, leaves people
unaffected , future pick of 6 names repeat names.
Comments
Post a Comment