Random module not working. ValueError: empty range

2019-01-26 07:26发布

In Python 2.7.1, I import the random module. when I call randint() however, I get the error:

ValueError: empty range for randrange() (1,1, 0) 

This error is caused by an error in the random.py module itself. I don't know how to fix it, not does reinstalling python help. I can't change versions.

can someone please give me code for a working module or tell me what to do?

4条回答
你好瞎i
2楼-- · 2019-01-26 07:53

random.randint(1, 0) returns an error because whenever you use random.randint(a, b) a must be less than b. Try changing random.randint(1, 0) to random.randint(0, 1) to get a valid result.

Click here for more information about random.randint

查看更多
Anthone
3楼-- · 2019-01-26 08:01

If you called randint() by itself, it will most definitely result in an error. You need to provide randint() with a range to choose from. randint(a, b), where a and b are integers, should work, and if it doesn't, your Python installation is broken.

It would also raise an exception if b is less than a. Think of it like you're supplying a range: it would make sense to put the lower bound first, right? So put the smaller bound first.

If you really want to compare your random module with the correct one, the source is at http://svn.python.org/view/python/branches/release27-maint/Lib/random.py?view=markup

查看更多
乱世女痞
4楼-- · 2019-01-26 08:02

You called randint like this:

 randint(1,0)

That tells randint to return a value starting as 1 and ending at 0. The range of numbers from 1 to zero is as you surely realize an empty range. Hence the error:

 empty range for randrange()
查看更多
太酷不给撩
5楼-- · 2019-01-26 08:18

Trust me, random works just fine. You are calling randint with b < a:

>>> random.randint(1, 0)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Python27\lib\random.py", line 228, in randint
    return self.randrange(a, b+1)
  File "C:\Python27\lib\random.py", line 204, in randrange
    raise ValueError, "empty range for randrange() (%d,%d, %d)" % (istart, istop
, width)
ValueError: empty range for randrange() (1,1, 0)

randint returns a value between the first argument and the second argument.

查看更多
登录 后发表回答