Random.randrange中的ValueError

时间:2012-05-29 14:33:53

标签: python random

def wordjumble(Wordlist, Hintlist, score):
    wordchoice = getword(Wordlist, Hintlist)
    high = len(wordchoice)
    low = -len(wordchoice)
    for i in range(10):
        position = random.randrange(high,low)
        print wordchoice[position]
    score = wordguess(wordchoice, score)
    return score

我收到一个值错误,我的任务是得到一个高低之间的随机数。 我的错误在哪里?

这是追溯:

Traceback (most recent call last): 
File "E:\Programming\Python\Worksheet 15\test.py", line 54, in
wordjumble(Wordlist, Hintlist, score) 
File "E:\Programming\Python\Worksheet 15\test.py", line 49, in wordjumble
position = random.randrange(high,low) 
File "E:\Portable Python 2.7.2.1\App\lib\random.py", line 217, in
randrange raise ValueError, "empty range for randrange() (%d,%d, %d)"
% (istart, istop, width) ValueError: empty range for randrange() (7,-7, -14)

5 个答案:

答案 0 :(得分:1)

您收到错误是因为您在线上反转了参数:

 position = random.randrange(high,low)

它应该是:

 position = random.randrange(low,high)

建议:大多数python参考文档都显示了代码示例。首先检查它们,因为它们可能会立即帮助您:
http://docs.python.org/library/random.html

亲切的问候,

答案 1 :(得分:1)

更改行

        position = random.randrange(high,low)

        position = random.randrange(low,high)

ETA:此代码还存在其他问题。如果wordchoice是一个单词(正如getword函数所暗示的那样),那么您的循环正在做的是在-len(wordchoice)len(wordchoice)-1之间选择一个随机数。如果你试图从单词中随机抽取一个字母,那么在0len(wordchoice)-1之间做一个随机数会更简单,甚至更简单,只做random.choice(wordchoice)

看起来循环正在从单词中挑选10个随机字母并打印它们(每个字母在一个单独的行上)。这意味着使用单词the最终会出现“混乱”,如:

h
t
t
e
h 
e
t
e
t
e

这总是有10个字母,并不保证它使用单词的每个字母一次(这可能是你的混乱所必需的)。如果不是通过替换选择10个字母,而是希望它通过更改字母的顺序来混淆单词(如函数标题wordjumble所暗示的那样),请查看this question好的解决方案。

答案 2 :(得分:0)

   random.randrange([start], stop[, step])
   Return a randomly selected element from range(start, stop, step). This is equivalent to          choice(range(start, stop, step)), but doesn’t actually build a range object.

答案 3 :(得分:0)

一般范围是lowhigh,您要查看randrange docs

您可以找到简单用法示例at Python Number randrange() Function

答案 4 :(得分:0)

high,low替换为low,high

def wordjumble(Wordlist, Hintlist, score):
    wordchoice = getword(Wordlist, Hintlist)
    high = len(wordchoice)
    low = -len(wordchoice)
    for i in range(10):
        position = random.randrange(low,high)
        print wordchoice[position]
    score = wordguess(wordchoice, score)
    return score