[Tutor] Why am I getting an infinite loop?

Denis spirou@aragne.com
Mon, 28 Aug 2000 01:40:15 +0200


Le Sun, Aug 27, 2000 at 07:12:21PM -0400, Christopher Keelan pianota:
> I'm working through an exercise in O'Reilly's "Learning Python".
> 
> When I test it by running the script, I get an infinite loop at the print
> statemnt. Any ideas why this is happening?
> 

Just an indentation problem :
Idle 0.6 wouldn't let you write that :
there's a automagic dedent when you write a break statement.

> Here's the code
> ---
> l=[1,2,4,8,16,32,64]
> d=5
> i = 0
> 
> print 'length of list is', len(l)
> while i < len(l):
>     if 2**d == l[i]:
>         print 'at index', i
>         break
>         i = i+1
>     else:
>         print d, 'not found'
> ---

try this as your while loop
> ---
while i < len(l):
    if 2**d == l[i]:
        print 'at index', i
        break
    i = i+1
else:
    print d, 'not found'
> ---

Logic, isn't it ? ;-)

Greetings from here.
-- 
Denis FRERE
P3B    : Club Free-Pytho-Linuxien Caroloregien http://www.p3b.org
Aragne : Internet - Reseaux - Formations  http://www.aragne.com