I have a python program here that unscrambles a word, but I'm not sure what is happening in a specific section.
In the section that is blockquoted and separated by headers below, I don't understand why the 'scrambling' of the word is put into a while loop - could it not work without the loop? Also, can someone explain everything happening inside of that while loop (while word:)?
import random
words = ('coffee', 'phone', 'chair', 'alarm')
word = random.choice(words)
correct = word
scramble = ""
while word: position = random.randrange(len(word)) scramble += word[position] word = word[:position] + word[(position + 1):]
print("The scrambled word is: ", scramble)
answer = input("What's your guess?: ")
def unscramble(answer):
while answer != correct and answer != "":
print("Sorry, incorrect.")
answer = input("Try again: ")
if answer == correct:
print("Good job, that is correct!")
unscramble(answer)
Let's look at the while loop one line at a time.
while word:
This is just a shorthand for saying while len(word) > 0
. It means that the loop will continue until word
is empty.
position = random.randrange(len(word))
This line uses the standard library random.randrange
function to get a (pseudo)random number between 0 and len(word) - 1
inclusive.
scramble += word[position]
Here, the character at the random position in the word is being added to the scrambled word.
word = word[:position] + word[(position + 1):]
Finally, this line deletes the randomly-chosen character from the original word using slicing. The expression word[:position]
means "the substring of word
up to (but not including) the index position
". So if position
is 3, then word[:position]
would be the first three characters of word as a string. Similarly, word[(position + 1):]
means "the substring of word
starting at index position + 1
".
The whole expression ends up being "word
except for the character at index position
", because you're concatenating the part of word
up to position
with the part of word
starting at position + 1
. Unfortunately, this is the most graceful way to delete a character from a string in Python.
To summarize: the while loop chooses a random character of the original word, adds it to the scrambled word, and deletes it from the original. It continues to do this until there are no characters left in the original.