I have a slight problem where a variable doesn't seem to be properly defined as a variable. When I try to print
the values of the variable WordLetters
, it doesn't return anything. When I try to print
the length of the variable, it returns 0
.
Initially I had a NameError
in terms of the WordLetters
variable, then I defined outside the try:
function, and now it returns no value. Could it be that try:
has its own scope? And if so, how would I append values to the WordLetters
list?
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.")
Martijn Pieters :
You are silently ignoring index errors by using except IndexError: pass. If any of your randomly picked words are shorter than 10 characters, you'll get an exception and WordLetters will not be set.\n\nEither set a default when that happens, or avoid indexing individual characters altogether; you could just use the list() function to create a list with all the individual characters of the word:\n\nWordLetters = list(RandomWord)\n\n\nwithout having to know up-front how many characters there are in the word.\n\nNote that unless you plan to mutate the list (change individual elements or add or delete elements from the list) you don't need to turn your string into a list of individual characters. You can always loop over a word or get the length; len(RandomWord) works, and so does for character in RandomWord: print(character).",
2015-10-06T14:54:13
Medallyon :
Ignoring IndexError doesn't help.\n\nMy solution is to check each word's length, like so:\n\nif len(RandomWord) == 2:\n WordLetters = [RandomWord[0], RandomWord[1]]\nelif len(RandomWord) == 3:\n WordLetters = [RandomWord[0], RandomWord[1], RandomWord[2]]\nelif len(RandomWord) == 4:\n WordLetters = [RandomWord[0], RandomWord[1], RandomWord[2], RandomWord[3]]\nelif len(RandomWord) == 5:\n WordLetters = [RandomWord[0], RandomWord[1], RandomWord[2], RandomWord[3], RandomWord[4]]\nelif len(RandomWord) == 6:\n WordLetters = [RandomWord[0], RandomWord[1], RandomWord[2], RandomWord[3], RandomWord[4], RandomWord[5]]\nelif len(RandomWord) == 7:\n WordLetters = [RandomWord[0], RandomWord[1], RandomWord[2], RandomWord[3], RandomWord[4], RandomWord[5], RandomWord[6]]\nelse:\n WordLetters = [RandomWord[0], RandomWord[1], RandomWord[2], RandomWord[3], RandomWord[4], RandomWord[5], RandomWord[6], RandomWord[7]]\n\n\nSomewhat lengthy, but it works.",
2015-10-06T14:44:10