[Tutor] newbie 'while' question

Matthew Richardson marichar@csusb.edu
Mon Jun 30 17:11:01 2003


On Mon, 2003-06-30 at 13:51, Kalle Svensson wrote:
> -----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?
> 
I see it now :)  the loop continues for an iteration beyond the string
and returns an index error.  The example provided earlier avoids this by
getting the length of the string and then printing it from the first
position until it reaches zero, rather than trying to count up from zero
(what I was trying to do).

Thanks,
Matt

-- 
Matt Richardson
Instructional Support Technician
Department of Art
CSU San Bernardino