Re: [Tutor] newbie 'while' question
by Eric L Howard other posts by this author
Jun 30 2003 9:57PM messages near this date
Re: [Tutor] newbie 'while' question
|
Re: [Tutor] newbie 'while' question
At a certain time, now past [Jun.30.2003-10:51:14PM +0200], kalle@[...].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@[...].org Advocate of the Theocratic Rule
_______________________________________________
Tutor maillist - Tutor@[...].org
http://mail.python.org/mailman/listinfo/tutor
Thread:
Matthew Richardson
Danny Yoo
Matthew Richardson
Kalle Svensson
Eric L Howard
Danny Yoo
Matthew Richardson
Matthew Richardson
Matthew Richardson
Danny Yoo
Matthew Richardson
Danny Yoo
Zak Arntson
Zak Arntson
Zak Arntson
Zak Arntson
|