randin值错误

2024-03-29 00:29:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个非常奇怪的错误,我不知道是什么。 这是我的代码:

def wordChoice():
    theme = themechoice
    word = theme[randint(0, len(theme) - 1)]

这是错误:

^{pr2}$

我到处找遍了,但什么也没找到。我也是一个新手,如果这是显而易见的事情,我很抱歉。在

编辑:

在我设置主题之前:

def themeChoice():
    n = 0
    for i in themes:
        n += 1
        print(str(n) + " - " + i)
    themechoice = themesToThemes[themes[int(input("Type the number corresponding to your chosen theme: ")) - 1]]
    print (themechoice)

Tags: 代码编辑lendef错误theme事情themes
1条回答
网友
1楼 · 发布于 2024-03-29 00:29:12

theme为空时,将发生此错误。在

>>> theme = []
>>> random.randint(0, len(theme)-1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "C:\Programming\Python 3.5\lib\random.py", line 218, in randint
    return self.randrange(a, b+1)
  File "C:\Programming\Python 3.5\lib\random.py", line 196, in randrange
    raise ValueError("empty range for randrange() (%d,%d, %d)" % (istart, istop, width))
ValueError: empty range for randrange() (0,0, 0)

在尝试从中随机选择元素之前,请确保theme中确实有元素。另外,考虑使用^{},而不是用randint手动生成索引。在

相关问题 更多 >