我有这个非常奇怪的错误,我不知道它是什么。 这是我的代码:
def wordChoice():
theme = themechoice
word = theme[randint(0, len(theme) - 1)]
这是错误:
Traceback (most recent call last):
File "C:\Users\Andrei\Documents\USB Backup\Python\Hangman.py", line 31, in wordChoice
word = theme[randint(0, len(theme) - 1)]
File "C:\Users\Andrei\AppData\Local\Programs\Python\Python35-32\lib\random.py", line 218, in randint
return self.randrange(a, b+1)
File "C:\Users\Andrei\AppData\Local\Programs\Python\Python35-32\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)
我到处搜索,但找不到任何东西。如果这是显而易见的话,我也有点新手了。
编辑:
在我为此设置主题之前:
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)
答案 0 :(得分:1)
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
实际上包含元素。另外,请考虑使用random.choice
而不是使用randint
手动生成索引。