2012-05-29 22 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