Reputation: 23
I'm currently learning Python from a book by Michael Dawson. Everything was clear and concise except when i got to an exercise called the 'Word Jumble Game'. This is the code that is confusing me.
import random
# create a sequence of words to choose from
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
# pick one word randomly from the sequence
word = random.choice(WORDS)
# create a variable to use later to see if the guess is correct
correct = word
# create a jumbled version of the word
jumble =""
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
What i don't understand is how the while:word works. This is the explanation given:
I set the loop up this way so that it will continue until word is equal to the empty string. This is perfect, because each time the loop executes, the computer creates a new version of word with one letter “extracted” and assigns it back to word. Eventually, word will become the empty string and the jumbling will be done.
I tried tracing the program (maybe its an obvious oversight on my behalf) but i cannot see how the 'word' eventually breaks out of the loop because as long as it has characters in it surely it would evaluate to True and be an infinite loop.
Any help is hugely appreciated guys as i have looked for answers everywhere and its been fruitless. Thanks in advance.
Upvotes: 2
Views: 120
Reputation: 11134
This three statement is what you are suffering to understand
jumble += word[position] # adding value of the index `position` to jumble
word[:position] # items from the beginning through position-1
word[(position + 1):] # items position+1 through the rest of the array
So, after each iteration, exactly one item is cut down from the original string word
. (word[position]
)
So, eventually you will end up with an empty word
string.
if you are not convinced yet, add a print statement at the end of every iteration. This should help you.
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
print word
Upvotes: 5
Reputation: 78
while word:
Loop block will be executed until word length is zero.
Note: This code acts like random.shuffle. from random import shuffle; shuffle(word)
Upvotes: 0