2011-12-19 200 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