python - I do not understand this piece of tutorial code? -


i'm learning python book michael dawson. clear , concise except when got exercise called 'word jumble game'. code confusing me.

import random      # create sequence of words choose     words = ("python", "jumble", "easy", "difficult", "answer", "xylophone")      # pick 1 word randomly sequence     word = random.choice(words)      # create variable use later see if guess correct     correct = word      # create jumbled version of word     jumble =""     while word:         position = random.randrange(len(word))         jumble += word[position]         word = word[:position] + word[(position + 1):] 

what don't understand how while:word works. explanation given:

i set loop way continue until word equal empty string. perfect, because each time loop executes, computer creates new version of word 1 letter “extracted” , assigns word. eventually, word become empty string , jumbling done.

i tried tracing program (maybe obvious oversight on behalf) cannot see how 'word' breaks out of loop because long has characters in surely evaluate true , infinite loop.

any hugely appreciated guys have looked answers everywhere , been fruitless. in advance.

this 3 statement suffering understand

jumble += word[position] # adding value of index `position` jumble word[:position] # items beginning through position-1 word[(position + 1):]   # items position+1 through rest of array 

so, after each iteration, 1 item cut down original string word. (word[position])

so, end empty word string.

if not convinced yet, add print statement @ end of every iteration. should you.

while word:     position = random.randrange(len(word))     jumble += word[position]     word = word[:position] + word[(position + 1):]     print word 

Comments

Popular posts from this blog

resizing Telegram inline keyboard -

command line - How can a Python program background itself? -

php - "cURL error 28: Resolving timed out" on Wordpress on Azure App Service on Linux -