[Tutor] while loop only executes once

Lloyd Hugh Allen lha2@columbia.edu
Wed, 19 Dec 2001 05:43:49 -0500

Brett Kelly wrote:
> ok, here's my loop.  it only goes through once and exits.
> (words is a dictionary with each letter of the alphabet corresponding to a
> different word)
> name = raw_input("Please enter your name: ")
> name.lower()
> for i in range(0, len(name)):
>     letter = name[i]
> while len(name) > 0:
>     print words[letter]
> name[i] = name[1:]
> i can't figure this out!!!
> please help, thanks!
> Brett
> --
> Sent through GMX FreeMail - http://www.gmx.net
> _______________________________________________
> Tutor maillist  -  Tutor@python.org
> http://mail.python.org/mailman/listinfo/tutor

*name is not being changed within the while loop. If you want it to be,
indent name[i]=name[1:]

*except that name is currently a string. Strings don't like it when you
assign a slice to a character in the string (or when you assign anything
to a character in the string).

Is this what you want? I don't know what kind of output you are looking
for, and couldn't figure out what the for loop was supposed to do.

----begin code below this line-----

words = {'a':'foo', 'b':'foo2', 'c':'foo3'}

name = raw_input("Please enter your name: ")

while len(name) > 0:
    print words[name[0]]
    name = name[1:]

----end code above this line------

----begin output------
Please enter your name: abc
----end output--------

I have a feeling that your troubles come from using two separated loops
when one will do, or from not nesting your loops if you want them to
interact with each other. A for loop is probably a better choice for the
above output, along the lines of

for letter in name:
    print words[letter]

(which is probably easier to understand than the double-indexed stuff in
the while loop above).