0

I'm relatively new to programming and decided to, on my own time, mess around and create a few basic functions of my own. I'm sure plenty of other variations exist, but I wanted to just make them my own way to learn. I am currently trying to write a function that displays all prime numbers within a certain Max value as a limit in a list. However, I seem to have a problem with my if statement in the while loop. I keep getting list index out of range and I am confused as to why. If someone could explain to me the reason, I would be incredibly grateful.

    #A function that will hopefully display all primes

def showPrimes(lim):
    """Displays all primes within the range (1, lim]
    """

    fullRange = list(range(2, lim + 1))

    q = 0
    k = 2

    while(q != lim):

        if(fullRange[q] % (q + 2) == 0 and fullRange[q] != (q + 2)):

            fullRange.pop(q) 

        q = q + 1

    return fullRange
Ashby H
  • 9
  • 1
  • 1
    Try `while q < len(fullRange) - 1`. Remember, the size of the list can change when you remove lements, and the start of 2 ensures that with your current code the last loop will always overflow. – anonymoose Oct 21 '17 at 16:07
  • Also, you could try looping through the range (without a `list()` call), and then adding the numbers that are prime to a list or a set. – anonymoose Oct 21 '17 at 16:08
  • 4
    Possible duplicate of [Python displays all of the prime numbers from 1 through 100](https://stackoverflow.com/questions/15963707/python-displays-all-of-the-prime-numbers-from-1-through-100) – eyllanesc Oct 21 '17 at 16:09
  • In addition, since `fullRange[0] = 2`, `fullRange[1] = 3`, etc. `fullRange[q] != (q + 2)` will always be false, so no numbers will ever be removed. The algorithm in the function @eyllanesc linked to is a good starting point. – anonymoose Oct 21 '17 at 16:10
  • 1
    Also - you can help yourself by putting in a `print` inside your while loop to show what q and lim are, and then put a print inside the `if` etc... then when it breaks you can see what it's done, what stuff currently is etc... – Jon Clements Oct 21 '17 at 16:12

0 Answers0