complete brain fart, it doesn't loop

Peter Otten __peter__ at web.de
Sun Jul 27 14:07:48 EDT 2014


Chris Angelico wrote:

> On Mon, Jul 28, 2014 at 3:53 AM, Martin S <shieldfire at gmail.com> wrote:
>> I have this snippet in my web application. Question is why doesn't the
>> stupid thing loop ten times? It loops exactly 1 time.
>>
>>   # Reset counter
>>     counter = 0
>>
>>     while counter <= 10:
>>
>>         return "<p>Long line with games</p>"
>>
>>         counter=counter+1
> 
> When you hit the 'return', it stops the function immediately :)

By the way, Python has something similar to a function that temporarily 
interrupts execution but preserves state. It's called generator. Compare:

>>> def f():
...     for i in range(3):
...             return "<p>Long line with games</p>"
... 
>>> f()
'<p>Long line with games</p>'
>>> def g():
...     for i in range(3):
...             yield "<p>Long line with games</p>"
... 
>>> g()
<generator object g at 0x7fe9b3e7b690>
>>> list(g())
['<p>Long line with games</p>', '<p>Long line with games</p>', '<p>Long line 
with games</p>']





More information about the Python-list mailing list