mjruss - 8 days ago 6

Python Question

I am making a program that finds prime numbers. The user is asked to provide a number greater than 2 (n) the program then makes a list starting at 2 and ending at the users number (n). In my program I am supposed to set a variable called current to 2 and then loop through the list looking for multiples of current and removing them. At the end of a loop I add 1 to current and the program loops again doing the same as before. The list is printed each time. My program works correctly (I am testing by using the number 10 as n) when it gets to the end 10 is left even though it should have been removed. Please help.

Here is my code:

`while True:`

global n

n = int ( input ( "Please enter a number larger than 2. " ) )

if n > 2:

break

else:

print ( "Your number is not larger than 2." )

continue

current = 2

myList = list ( range ( 2, n + 1 ) )

while current < n:

if current == []:

break

for i in reversed ( range ( len( myList )-1 ) ):

if myList[i] % current == 0 and myList[i] != current and ( myList[i] / current ).is_integer(): myList.pop(i)

print ( myList )

current = current + 1

Answer

`for i in reversed ( range ( len( myList )-1 ) ):`

should be
`for i in reversed ( range ( len( myList ) ) ):`

range by default doesn't include the last number: `range(5)`

gives `0,1,2,3,4`

To make it only output a line when it makes a change:

```
if myList[i] % current == 0 and myList[i] != current and ( myList[i] / current ).is_integer():
myList.pop(i)
print ( myList )
```

If you do the print inside the if statement, then only when it makes a change will it display the new list.