Stuck? Need help? Ask questions on our forums.

Read Post

Python

Moderators: None (Apply to moderate this forum)
Number of threads: 249
Number of posts: 807

This Forum Only
Post New Thread

Report
Why doesn't the loop work? Posted by falcon3166 on 4 Jul 2008 at 4:22 PM
Why doesn't the loop in the following code work?

#Finds out what numbers are prime.
primes = [2,3,5,7,11,13,17,19,23]
finish = int(raw_input("What number would you like to check to? "))
start = 24
while start >= finish:
    x = 0
    while start % primes[x] != 0:
        if IndexError:
            break
        else:
            x = x + 1
    else:
        primes.append[start]
    start = start + 1
print primes


When run, it just prints out the default set of primes after taking the number you want the program to check up to.
Swat spam before it fills your inbox!
Reply
Report
Re: Why doesn't the loop work? Posted by Gabe on 25 Aug 2008 at 3:20 PM
IndexError is a class whose instance is raised as an exception if an invalid index is used on a sequence, therefore it cannot be false as a logical expression. Use try and except instead:
 
#Finds out what numbers are prime.
primes = [2,3,5,7,11,13,17,19,23]
finish = int(raw_input("What number would you like to check to? "))
start = 24
while start >= finish:
    x = 0
    try:
        while start % primes[x] != 0:
           x = x + 1
    except IndexError:
        primes.append(start)
    start = start + 1
print primes

Reply




corner
© 1996-2008. All rights reserved. Reproduction in whole or in part, in any form or medium without express written permission is prohibited.
Violators of this policy may be subject to legal action. Please read our Terms Of Use and Privacy Statement for more information.
Publisher: Lars Hagelin.
bootstrapLabs Logo A bootstrapLabs project.