这个Python错误是什么意思?

时间:2011-12-19 14:45:41

标签: python-3.x

这是我的测试代码(Python 3.2)

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)

我无法弄清楚这意味着什么,或者我做错了什么。

2 个答案:

答案 0 :(得分:5)

您告诉您的程序创建1到5050之间的随机数并将其存储在a中。之后你想获得1到5050-a之间的另一个随机数,现在如果a是5050,你会要求它生成1到0之间的随机数。

reference

答案 1 :(得分:4)

简答:错误表示a有时等于5050

长答案: randint()会返回一个位于提供范围内的随机数。如果上限小于下限,则函数失败,因为没有要处理的实际范围。

您的第一个电话会将15050(含)之间的随机数存储到a。您的第二个电话会将15050 - a(包括)之间的随机数存储到b。如果第一个调用返回5050,则第二个调用将失败,因为提供的范围将无效。

相关问题