Hi,
I'm teaching myself Python mainly for to use as a hobby. I'd like to do
graphical programs eventually and maybe some simple graphic games. I feel I'm
doing well with the tutorial I'm using but it would be nice to have some real
people to ask questions and opinions, so on that note, I'm having a little
trouble understanding the following code. I grasp the basics of what it does
but am wondering if someone could explain it in simpler terms..
In the tutorial, I'm using Tuples and there is a Word Jumble game given to show
how this can be used. A tuple of words is created:
WORDS = ("python", "jumble", "easy", "difficult", "answer", "xylophone")
correct=word
Then a variable that will hold the jumbled word is defined: jumble=' '
Ok, then a variable: word=random.choice(WORDS) is created to pick a random
element from WORDS. I get this part.
Now here is the code I'm having trouble following:
while word:
position = random.randrange(len(word))
jumble += word[position]
word = word[:position] + word[(position + 1):]
position = random.randrange(len(word)). This will create a starting point for
the program to pick a letter out of a word at random using the length of the
word as a range I think. Like if the word is 'python' and since it has 6
letters, random.randrange(len(word)) will pick a random starting point such as
the letter 'y' for example. It's gonna be inside a while loop, so the next time
it runs, 'python' will be 'pthon' and the random range will be 5 letters and on
down till there is no more letters, is this right?
Ok, so everyone of the letters that was 'extracted' from the word 'python' will
be put into the variable 'jumble' that was defined as empty.
This is the part that troubles me:
word = word[:position] + word[(position + 1):]
I know basically it is creating a new string through the while loop for
extracint letters. But I don't feel I understand it fully, The expression is
confusing to me. Here is an excerpt from the tutorial that explains it and
confuses me more:
"The next line in the loop,
word = word[:position] + word[(position + 1):]
creates a new version of word minus the one letter at position position. Using
slicing, the computer creates two new strings from word. The first slice,
word[:position], is every letter up to, but not including, word[position]. The
next slice, word[(position + 1):], is every letter after word[position]. These
two string are joined together and assigned to word, which is now equal to its
old self, minus the one letter word[position]."
Can someone explain this in simpler terms? I'm sorry this is so lengthy for my
first post:)
Any help will be appreciated
Thanks,
Doug
_______________________________________________
Tutor maillist - [email protected]
http://mail.python.org/mailman/listinfo/tutor