[Tutor] while loop only executes once

Gregor Lingl glingl@aon.at
Mon Nov 19 17:51:53 CET 2012


I tried to do, what you did:

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

Please enter your name: Brett
>>> name
'Brett'
>>> name.lower()
'brett'
>>> name
'Brett'

So we see that the content of name didn't change.
Presumably you meant:

>>> name = name.lower()

we continue ...

>>> for i in range(0, len(name)):
      letter = name[i]


>>> letter
't'
>>>

So you see, after this for-loop is finished, you
have a single value in the variable letter: the last
one of you name. The letters before r were also in
letter, but are now overwritten.
Suppose now - for sake of brevity - words were this:

>>> words = { 'a':'apple', 'b':'ball', 'e':'egg', 'r':'rust', 't':'tea' }
>>>

Then the while loop acts as follows:

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

tea
ea
tea
tea
tea
tea
tea
tea
tea
tea
tea
tea
Traceback (most recent call last):
  File "<pyshell#9>", line 2, in ?
    print words[letter]
  File "D:\Python21\Tools\idle\PyShell.py", line 676, in write
    self.shell.write(s, self.tags)
  File "D:\Python21\Tools\idle\PyShell.py", line 667, in write
    raise KeyboardInterrupt
KeyboardInterrupt
>>>

I had to interrupt it by Ctrl-C, because the condition for
performing the body:  len(name) > 0  remains true forever.
So we have an infinite loop.

The next statement:

>>> name[i] = name[1:]
Traceback (most recent call last):
  File "<pyshell#10>", line 1, in ?
    name[i] = name[1:]
TypeError: object doesn't support item assignment
>>>

again results in an error, because in Python
strings ar immutable objects. Therfore you cannot
change single characters within a string by assignment.

... But, by the way, what did you intend to arrive at?

Gregor



Brett Kelly schrieb:

> 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





More information about the Tutor mailing list