954,525 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

while loop question

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
[php]
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):][/php]

here is where I am a little unsure. is the statement
[php]
while word:[/php]
the same as
[php]while word != "":[/php]

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

shanenin
Posting Whiz in Training
217 posts since May 2005
Reputation Points: 10
Solved Threads: 17
 

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.

shanenin
Posting Whiz in Training
217 posts since May 2005
Reputation Points: 10
Solved Threads: 17
 

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.

vegaseat
DaniWeb's Hypocrite
Moderator
5,989 posts since Oct 2004
Reputation Points: 1,345
Solved Threads: 1,417
 

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

shanenin
Posting Whiz in Training
217 posts since May 2005
Reputation Points: 10
Solved Threads: 17
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You