[Tutor] newbie 'while' question

Eric L Howard elh@outreachnetworks.com
Mon Jun 30 17:58:02 2003


At a certain time, now past [Jun.30.2003-10:51:14PM +0200], kalle@lysator.liu.se spake thusly:
> -----BEGIN PGP SIGNED MESSAGE-----
> Hash: SHA1
> 
> [Matthew Richardson]
> > s = raw_input('Enter a name: ')
> > x = 0
> > while x >= 0:
> >     print s[x]
> >     x += 1
> > 
> > The error is expected because the counter goes on beyond the number of
> > characters in the string and runs out of stuff to print.  Got that part
> > of it.  How can I count the number of characters in the string?  Then
> > the while statement could be changed to
> > 
> > while x <= NumOfChar:
> >     dosomestuff
> 
> This is very close to the correct solution.  You get the number of
> characters in the string with the len() built-in function.  But
> 
>   s = raw_input('Enter a name: ')
>   x = 0
>   while x <= len(s):
>       print s[x]
>       x += 1
> 
> will still result in an IndexError (even though it's close to being
> correct).  Do you see why?

[newbie swing ;-)]

I know it works, but would it be bad to do something like
       
s = raw_input('Enter a name: ')
    for x in range(0, len(s)):
    print s[x]

There's no need to initialize x, or declare our math statement in the code.
Thoughts, corrections?

       ~elh

-- 
Eric L. Howard           e l h @ o u t r e a c h n e t w o r k s . c o m
------------------------------------------------------------------------
www.OutreachNetworks.com                                    313.297.9900
------------------------------------------------------------------------
JabberID: elh@jabber.org                 Advocate of the Theocratic Rule