Is_prime list problems



A "list index out of range" error always appears when I run it with a number.

I tried print number[i] to see what number it is putting out but it always prints out numbers farther down the list than I expect so now I am stuck.

def is_prime(x):
    n = 2
    number = []
    if x < 2:
        return False
        while x > n:
            n = n + 1
            print number
        for i in number:
            if x % number[i] == 0:
                return False
                return True


I'm not quite sure after looking at this for a bit.

Instead of for i in number: try using for i in range(1,x):. For loops jump all around the list at random. Using range() lets you step through sequentially. I'm new, too, so I don't know why this is the case.

Also, definitely sprinkle print statements all throughout your code so you can see what's happening at any given time. That's the only way I was able to finish this assignment.


posting answers like that is unfortunately not allowed, see guidelines


i like your approach, there are only 3 issues

i will contain values from the list, not indexes. currently you thread i like indexes

your function will fail for x=2, given your while loop condition is false, so you will need to write a special case for x=2 to return True

a function ends the moment a return keyword is reached, so your function ends in the first iteration of the loop. But for a number to a prime number, the whole loop should finish running.

so we want to return True after the for loop, not in the first iteration if the first value from your number list is tested

you can also use range like @rickymccallum87 suggested. But i think you are pretty close with what you currently have


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.