On Thu, May 16, 2013 at 1:03 PM, Arvind Virk <arvind.s.v...@hotmail.co.uk>wrote:
import random > > WORDS = ('python','jumble','easy','difficult','lower','high') > word = random.choice(WORDS) > correct = word > jumble = "" > > while word: > position = random.randrange(len(word)) > jumble += word[position] > word = word[:position] + word[(position+1):] > > ====== > > I cannot understand what it is trying to do in the while loop. > If the word was python and position lets say was 3 then jumble would = > python(3). I cannot understand what the next line does! Please help! > > First, about "while word" - A 'while' loop runs as long as its condition evaluates to True; an explanation of what evaluates to True can be found here: http://docs.python.org/2/library/stdtypes.html, but for our purposes it boils down to "as long as 'word' is not an empty string, keep going". Second, what it's doing inside that while loop - it's picking a random letter out of 'word', adding it to the end of 'jumble', and then removing it from 'word'. It's doing it by means of slices: it takes all of 'word' up to (but not including) 'position', then adds all of 'word' starting one character AFTER 'position'. 'word' is now one character shorter than it started out; keep this up long enough and you'll be left with an empty string, which evaluates to False - and the 'while' loop terminates. This is definitely not the most efficient way to do things, but it's a pretty good introduction to slices (which are awesome, by the way.) There's a very good introduction to Python's slice notation about halfway down this page: http://docs.python.org/2/tutorial/introduction.html, in section 3.1.2 "Strings". Just remember that lists and indices start with 0, not 1, and you'll be on your way. Finally, as Ramit mentioned, print statements (or print() functions, if you're on Python 3) are your friend! Don't be afraid or ashamed to put in lots of them whenever you're not sure what your code is doing! (Just remember to take out the unnecessary one when you're done.)
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor