变量不想定义?

时间:2015-10-06 14:29:36

标签: python list variables python-3.x global-variables

我有一个小问题,其中变量似乎没有被正确定义为变量。当我尝试print变量WordLetters的值时,它不会返回任何内容。当我尝试print变量的长度时,它会返回0

最初我在NameError变量方面有一个WordLetters,然后我在try:函数之外定义,现在它没有返回任何值。是try:有自己的范围吗?如果是这样,我将如何将值附加到WordLetters列表?

RandomWord = random.choice(Words)
try:
  WordLetters = [RandomWord[0], RandomWord[1], RandomWord[2], RandomWord[3], RandomWord[4], RandomWord[5], RandomWord[6], RandomWord[7], RandomWord[8], RandomWord[9]]
except(IndexError):
  pass

print("Word: " + "".join(WordLetters))
print("The word is " + str(len(WordLetters)) +  " letters long.")

3 个答案:

答案 0 :(得分:5)

您使用except IndexError: pass默默忽略索引错误。如果您随机挑选的任何字词短于10个字符,您将收到例外情况,并且不会设置WordLetters

在发生这种情况时设置默认,或者避免完全索引单个字符;您可以使用list()函数创建一个列表,其中包含单词的所有单个字符:

WordLetters = list(RandomWord)

无需事先知道单词中有多少个字符。

请注意,除非您计划改变列表(更改单个元素或添加或删除列表中的元素),否则您不需要将字符串转换为单个字符列表。你总是可以循环一个单词或获得长度; len(RandomWord)有效,for character in RandomWord: print(character)也有效。

答案 1 :(得分:-2)

忽略IndexError没有帮助。

我的解决方案是检查每个单词的长度,如下所示:

if len(RandomWord) == 2:
  WordLetters = [RandomWord[0], RandomWord[1]]
elif len(RandomWord) == 3:
  WordLetters = [RandomWord[0], RandomWord[1], RandomWord[2]]
elif len(RandomWord) == 4:
  WordLetters = [RandomWord[0], RandomWord[1], RandomWord[2], RandomWord[3]]
elif len(RandomWord) == 5:
  WordLetters = [RandomWord[0], RandomWord[1], RandomWord[2], RandomWord[3], RandomWord[4]]
elif len(RandomWord) == 6:
  WordLetters = [RandomWord[0], RandomWord[1], RandomWord[2], RandomWord[3], RandomWord[4], RandomWord[5]]
elif len(RandomWord) == 7:
  WordLetters = [RandomWord[0], RandomWord[1], RandomWord[2], RandomWord[3], RandomWord[4], RandomWord[5], RandomWord[6]]
else:
  WordLetters = [RandomWord[0], RandomWord[1], RandomWord[2], RandomWord[3], RandomWord[4], RandomWord[5], RandomWord[6], RandomWord[7]]

有点冗长,但它确实有效。

答案 2 :(得分:-2)

怎么样:

aword = 'hello world'
randomWord = []
for i in range(len(aword)):
    randomWord.append(random.choice(aword))

print ''.join(randomWord)
print len(randomWord)