[Tutor] newbie 'while' question

Matthew Richardson marichar@csusb.edu
Mon Jun 30 18:19:01 2003


On Mon, 2003-06-30 at 14:20, Danny Yoo wrote:
> > 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!

I knew I should have paid more attention in math...

Anyway, here is what I've got based on your excellent direction:

s = 'something'
x = 0
while x < len(s):
    print s[x]
    x += 1

Which works great.  I'm still stuck on how to do Zak's method of
manipulating the string, but starting to feel better about 'while' now.

Thanks,
Matt

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