[Tutor] newbie 'while' question
Kalle Svensson
kalle@lysator.liu.se
Mon Jun 30 16:52:01 2003
-----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?
Peace,
Kalle
- --
Kalle Svensson, http://www.juckapan.org/~kalle/
Student, root and saint in the Church of Emacs.
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.0.7 (GNU/Linux)
Comment: Processed by Mailcrypt 3.5.6 <http://mailcrypt.sourceforge.net/>
iD8DBQE/AKK7dNeA1787sd0RAqFHAKDNtLk7g7lnjTB1iGmqzvsUlmwL7ACgvp50
Bv40Lrsbna01B7sJenUN5bE=
=eDEp
-----END PGP SIGNATURE-----