0

So the idea is to make a function that returns all prime numbers between any two numbers (inclusive). Below, I'll put the function I wrote correctly, and the one I wrote incorrectly.

The mistake I made with the incorrect one is with the indentation of the "else" statement. But I'm not sure why one is correct and the other is not!

I'm also curious about the output I am getting from the incorrect function, which shows mostly duplicates of prime numbers but occasionally throws in a single number that is NOT a prime number, but rather a number divisible by 3 and another prime number. I have been trying to wrap my head around how the function produced this result (so I can understand the mistake), but I'm stumped!

Any help would be much appreciated

##This is the correct version: ##########################

def primefinder(start, end):                   
    primes = []
    for number in range(start, end +1):
        if number > 1:
            for i in range(2, number):
                if number % i == 0:
                    break
            else:                            
                primes.append(number)
    return primes


## This is the incorrect version:##############

def primefinder(start, end):
    primes = []
    for number in range(start, end +1):
        if number > 1:
            for i in range(2, number):
                if number % i == 0:
                    break
                else:                     ##<--This is my mistake##
                    primes.append(number)
    return primes

  • 2
    Does this answer your question? [Why does python use 'else' after for and while loops?](https://stackoverflow.com/questions/9979970/why-does-python-use-else-after-for-and-while-loops) – Mike Scotty Nov 30 '20 at 15:50
  • I strongly recommend opening your program in a graphical debugger, and single-stepping through it while looking a list of the values of the local variables (`i`, `number` and the like). A common free choice is to use PyCharm, but it's by no means the only one. Learning to use a debugger is an important skill which will serve you well when you start to work on programs too long to fit into a StackOverflow quesiton. – Arthur Tacca Nov 30 '20 at 16:01

2 Answers2

0

Python is indentation-sensitive. If you change the indentation, then the code itself changes. Your first code has the else corresponding to the for, creating a for...else loop that only appends the prime to primes if the loop didn't break (if the loop encountered a break that means a factor was found so it's not prime).

In your incorrect version, the else is indented one extra, so it corresponds to the if, which means that as long as the number has a factor that it isn't divisible by (such as 8 not being divisible by 3), then it'll append to the list, once for every factor it isn't divisible by.

Aplet123
  • 33,825
  • 1
  • 29
  • 55
0

Any help would be much appreciated

When in doubt you might use help in interactive mode. In this case launch python and do help("for") to get following information:

The "for" statement
*******************

The "for" statement is used to iterate over the elements of a sequence
(such as a string, tuple or list) or other iterable object:

   for_stmt ::= "for" target_list "in" expression_list ":" suite
                ["else" ":" suite]

The expression list is evaluated once; it should yield an iterable
object.  An iterator is created for the result of the
"expression_list".  The suite is then executed once for each item
provided by the iterator, in the order returned by the iterator.  Each
item in turn is assigned to the target list using the standard rules
for assignments (see Assignment statements), and then the suite is
executed.  When the items are exhausted (which is immediately when the
sequence is empty or an iterator raises a "StopIteration" exception),
the suite in the "else" clause, if present, is executed, and the loop
terminates.
...

and so on, please note that this will work only if iteration ended due to exhaustion, not when you break-ed from your loop. Consider that

for x in [1,2,3]:
    print(x)
else:
    print("else")

will print "else" at end, whilst

for x in [1,2,3]:
    print(x)
    break
else:
    print("else")

will not.

Daweo
  • 31,313
  • 3
  • 12
  • 25