用于绝对初学者的Python第5章挑战#1:出现错误

时间:2016-02-20 03:19:11

标签: python python-3.x

第5章,电子书名为"绝对初学者的Python编程" 挑战"创建一个以随机顺序打印单词列表的程序。 该程序应打印所有单词,不要重复任何单词。"

对于这个挑战,我做了这个code in right and output in left 我不知道这些错误是什么以及如何修复它们。那么如何帮助自己解决这些问题呢。

代码: -

import random
WORDS = ["OVERUSED", "CLAM", "GUAM", "TAFFETA", "PYTHON"]
x = len(WORDS) + 1
count = 0
if count == x:
    exit(0)
while count < int(x):

    word = random.choice(WORDS)
    WORDS.remove(word)  
    print(word)
    count += 1

**Output:-**
root@kali:~/Desktop/Projects# python3 randomWords.py
PYTHON
OVERUSED
TAFFETA
GUAM
CLAM
Traceback (most recent call last):
  File "/usr/lib/python3.4/random.py", line 253, in choice
    i = self._randbelow(len(seq))
  File "/usr/lib/python3.4/random.py", line 230, in _randbelow
    r = getrandbits(k)          # 0 <= r < 2**k
ValueError: number of bits must be greater than zero

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "randomWords.py", line 9, in <module>
    word = random.choice(WORDS)
  File "/usr/lib/python3.4/random.py", line 255, in choice
    raise IndexError('Cannot choose from an empty sequence')
IndexError: Cannot choose from an empty sequence

1 个答案:

答案 0 :(得分:1)

您将x定义为len(WORDS) + 1,但您的计数从0开始。因此,您试图获得1个太多的随机单词。请尝试使用x = len(WORDS)。另外,您可以说while count < x:x已经是整数。