I am trying to follow this code I am reading in a book. First I will show you the code as the book has it. This is for a word jumble program. This algorythm I am refering to jumbles a word

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):]

here is where I am a little unsure. is the statement

while word:

the same as

while word != "":

assuming the above two statments are the same. I am haveing trouble seeing why the variable word will ever evaluate to an emptly set. It seems like the while loop would concatenate forever, building a large and larger word. Any help in understanding this would be appreciated :-)

I am embarresed to say how long this took me to figure out. everytime it loops, one letter is removed from the variable word. Eventually it becomes an emptly set, then the loop stops.

Many times you can insert a temporary print statement to show what is going on. Here a test print inside the loop ...

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:
    print word,'  ', jumble   # for test only
    position = random.randrange(len(word)) 
    jumble += word[position] 
    word = word[:position] + word[(position + 1):]


print jumble

The empty string would return a None (Python's version of NULL) which is evaluated as boolean False, so the loop stops.

thanks for the suggestion. That technique should come in handy.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.