Why doesn't the loop work? - Programmers Heaven

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!

Categories

Why doesn't the loop work?

falcon3166falcon3166 Posts: 22Member
Why doesn't the loop in the following code work?

[code]
#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
[/code]

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!

Comments

  • GabeGabe Posts: 61Member
    [b]IndexError[/b] 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 [b]try[/b] and [b]except[/b] instead:
    [code]
    #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
    [color=Red]try:[/color]
    while start % primes[x] != 0:
    x = x + 1
    [color=Red]except IndexError:[/color]
    primes.append(start)
    start = start + 1
    print primes
    [/code]
Sign In or Register to comment.