简体   繁体   中英

Why does a function return the error “list index out of range” in Python?

This code was written in Python 3. I am trying to find the 10001st prime number.

#10001st prime number
mylist=[]
def prime_index(n):
    for i in range(99**99):
        for x in range(2, int(i**1/2)):
            if i % x == 0:
                return False
            return True
            mylist.append(i)
        n=int(n+1)
        print(mylist[n])
        break
prime_index(10001)

When I run, it says "list index out of range", referring to print(mylist[n]) . However I have been adding primes to the list along the way in the mylist.append(i) . So can someone tell me what is the problem here because I do not understand what is going on. Is 99**99 too small? Or more subtle problem with code?

99**99 is not too small; if you actually print it, you're well beyond what you need (if you tried to run it out, you'd never finish, it's 657 bits of work). But your loop makes no sense; your inner loop will return either True or False immediately if it executes even once.

"Luckily" for you, it never executes even once. The first outer loop sets i to 0 the first time, so the inner loop doesn't run at all (side-note, you probably want i ** (1/2) , not i ** 1 / 2 ; exponentiation has higher precedence than division). Because it doesn't run, you end up indexing into an empty list (and asking for index 10001 no less).

There are far too many problems in this code to address them all; look for other trial division prime finding code to get an idea of what it should look like.

The problem is that you try to print out the 10001st element as soon as you find (or not) the first prime. Also, note that you return from the routine without finding any prime number -- if you were to get that far. There is no way to reach the append statement.

You got to the print statement only because your first iteration has i = 0, so you don't enter the for loop at all.

Please follow the posting guidelines: take the time to research how to generate prime numbers. It can be much faster than you're doing, and will give you a nice, succinct bit of code to put into your program.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM