(Learner-here) Lists + Functions = headache

Bradley Wright bradley.wright.biz at gmail.com
Sun May 5 21:30:04 EDT 2013


On Sunday, May 5, 2013 9:24:44 PM UTC-4, Bradley Wright wrote:
> On Sunday, May 5, 2013 9:21:33 PM UTC-4, alex23 wrote:
> 
> > On May 6, 10:59 am, Bradley Wright <bradley.wright.... at gmail.com>
> 
> > 
> 
> > wrote:
> 
> > 
> 
> > > def fizz_cout(x):
> 
> > 
> 
> > >     count = 0
> 
> > 
> 
> > >     for item in x:
> 
> > 
> 
> > >         while item == "fizz":
> 
> > 
> 
> > >             count += 1
> 
> > 
> 
> > >             return count
> 
> > 
> 
> > >
> 
> > 
> 
> > > Please remember that i am a eager beginner, where am i going wrong?
> 
> > 
> 
> > 
> 
> > 
> 
> > There are several problems with your code:
> 
> > 
> 
> > 
> 
> > 
> 
> > >     for item in x:
> 
> > 
> 
> > >         while item == "fizz":
> 
> > 
> 
> > >             count += 1
> 
> > 
> 
> > 
> 
> > 
> 
> > The `for` takes an item out of the list `x`. If that item is the
> 
> > 
> 
> > string 'fizz', it increments count. As it's a `while` loop, it will
> 
> > 
> 
> > continue to increment for as long as `item` is 'fizz'. Since the while
> 
> > 
> 
> > loop doesn't look up another list item, it will remain as 'fizz' until
> 
> > 
> 
> > the end of time. Well, it would except for your second bug:
> 
> > 
> 
> > 
> 
> > 
> 
> > >         while item == "fizz":
> 
> > 
> 
> > >             count += 1
> 
> > 
> 
> > >             return count
> 
> > 
> 
> > 
> 
> > 
> 
> > The very first time it encounters a list item that is 'fizz', it adds
> 
> > 
> 
> > one to `count`, then exits the function passing back `count`.
> 
> > 
> 
> > 
> 
> > 
> 
> > You want to move the return to _outside_ the for loop, and you want to
> 
> > 
> 
> > change your `while` condition to an `if` instead.
> 
> 
> 
> Thank you Alex - much appreciated, about to implement right now!

Aha! lessons learned - got it!



More information about the Python-list mailing list