[Tutor] newbie 'while' question
Danny Yoo
dyoo@hkn.eecs.berkeley.edu
Mon Jun 30 17:21:03 2003
> Here's what I've got for the second scenario:
>
> 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.
Hi Matthew,
Ok, so that means that we want:
###
while some_expression_that_is_false_when_x_is_too_large:
print s[x]
x += 1
###
The expression that we have, right now:
x >= 0
is true as long as x is either positive or zero. ("nonnegative"). The
only problem is that this will always be true: nothing in the loop's body
ever causes x to become negative. *grin*
'x' is always increasing, hence our program breaks when it tries to print
nonexistant characters. So we need to choose a different condition,
something that is true only until the index reaches the end of the word.
That is, instead of
"Matthew Richardson"
(------------------------------------------>
0 infinity
We want to bound x's range to just:
"Matthew Richardson"
(------------------)----------------------->
0 infinity
In mathematical terms, we'd say that we'd like a half-open range,
0 <= x < length of "Matthew Ricahrdson"
And we'll find that the equivalent expression in Python is very similar to
this. *grin*
I hope this gives some hints on how to correct the while 'condition'
expression. Good luck!