2011-12-19 130 views
0

這是我的測試代碼(Python的3.2)這個Python錯誤是什麼意思?

import random 

def singleMatch(): 
    a = random.randint(1, 5050) 
    b = random.randint(1, 5050-a) 
    c = 5050-a-b 

    h = [a, b, c] 
    print(h) 
    computer = [841, 842, 3367] 

    score = 0 

    for i, j in zip(computer, h): 
     if i > j: 
      score = score + 1 

    if score == 2: 
     return 1 
    else: 
     return 0 



def match(n): 
    matchScore = 0 
    for i in range(n): 
     s = singleMatch() 
     matchScore = matchScore + s 
    return matchScore 

x = match(10000) 
print(x) 

當我運行代碼,我有時會收到此錯誤:

Traceback (most recent call last): 
    File "D:\Ercan\blotto.py", line 32, in <module> 
    x = match(10000) 
    File "D:\Ercan\blotto.py", line 28, in match 
    s = singleMatch() 
    File "D:\Ercan\blotto.py", line 5, in singleMatch 
    b = random.randint(1, 5050-a) 
    File "C:\Python32\lib\random.py", line 215, in randint 
    return self.randrange(a, b+1) 
    File "C:\Python32\lib\random.py", line 193, in randrange 
    raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width)) 
ValueError: empty range for randrange() (1,1, 0) 

我無法弄清楚這是什麼意思,或者我做錯了。

回答

5

你正在告訴你的程序創建一個介於1和5050之間的隨機數並存儲在一個。然後你想獲得1和5050-A之間的另一個隨機數,現在如果是5050,你會問它來生成隨機數1和0

4

簡短的回答之間

reference的錯誤意味着a有時等於5050

長答案:randint()返回位於提供的範圍內的隨機數。如果上限小於下限,則函數失敗,因爲沒有實際的範圍要處理。

您的第一個電話將15050(含)之間的隨機數存儲到a。您的第二個電話將15050 - a(含)之間的隨機數存儲到b。如果第一個呼叫返回5050,則第二個呼叫將失敗,因爲提供的範圍將無效。

+0

謝謝。現在我想知道,爲什麼我是「那個」愚蠢的。 – blackened 2011-12-19 15:04:28