2012-05-29 20 views
0
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 

我收到一个值错误,我的任务是得到一个高位和低位之间的随机数。 我的错误在哪里?ValueError in random.randrange

这里是回溯:

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) 
+6

是,其中*是*你的错误? :-) ..你能提供你得到的Traceback /错误信息吗? – Levon

+0

阅读[random.randrange](http://docs.python.org/library/random.html#random.randrange)的文档。 –

+0

回溯(最近呼叫最后): 文件“E:\ Programming \ Python \ Worksheet 15 \ test.py”,第54行,在 wordjumble(Wordlist,Hintlist,score) 文件“E:\ Programming \ Python \ Worksheet 15 \ test.py“,第49行,wordjumble position = random.randrange(high,low) 文件”E:\ Portable Python 2.7.2.1 \ App \ lib \ random.py“,第217行,in randrange raise ValueError,“randrange()(%d,%d,%d)的空范围” ValueError:randrange()(7,-7,-14)的空范围 – Geostigmata

回答

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以获得更好的解决方案。

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. 
+0

我相当新的python和一般编程,因为我很抱歉一个新手问题。任何人都可以给我一个例子如何解决它? – Geostigmata

+0

random.randrange(低,高)绝对随机.randrange(高,低) –

+0

有些字换行怎么样? –

1

因为你推翻了线的参数你得到一个错误:

position = random.randrange(high,low) 

它应该是:

position = random.randrange(low,high) 

建议:大部分的python参考文档都显示了代码的例子。检查出来,第一个,因为他们可以帮助你马上:
http://docs.python.org/library/random.html

亲切的问候,

+0

谢谢你,它解决了这个问题! – Geostigmata

0

更换high,lowlow,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