2016-07-27 2 views
-3

これは本当に奇妙なエラーですが、私はそれが何であるか分かりません。 これは私のコードです:ValueError with randint

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) 

私はどこでも検索したが、私は何かを見つけることができません。私はまた、それが明らかな何かだったので、ごめんなさいnewbのようなものです。

編集:私はこれにテーマを設定する前に

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

あなたは 'randint(0、0)'を求めています。 'len(theme)'は1であると思われるので、[0;で乱数を生成することはできません。 0 [ – BusyAnt

+0

これは 'randint(0、-1)'から得たもので、 'randrange(0,0)'に変換されます。解は意味をなさないので、その範囲の乱数を試して取得することではありません。 – khelwood

答えて

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が実際にランダムにそれから要素を選択しようとする前にその中の要素を持っていることを確認してください。また、手動でrandintのインデックスを生成する代わりにrandom.choiceを使用することを検討してください。