What is wrong with this prime number generator code?

for i in range (1, num+1):
    for j in range (2, i):
        if i%j==0:
            print (i)


The most important step when solving a problem is to identify it. What happens when you try running the code? How is that different from what you expect to happen?

I can see two things that go wrong. First, the output doesn’t have 2 in it, and second, the outputs get written multiple times (and include all odd numbers, not just prime numbers).

For the first problem, think about the for j in range (2, i): loop. When we test 2, there won’t be any values in that range, because we ask for range(2, 2), and ranges do not include the “stop” value. (There aren’t any numbers that are greater than or equal to the start value of 2, and also less than the stop value of 2.)

For the second problem, think carefully about the structure of the loop. We will print(i) for each j value that doesn’t cause the loop to break, but instead it needs to print once, only if the loop didn’t break at all. (Do you understand why?) There are a few ways to do this; perhaps you can think of some? (Note: the reason we only see odd numbers in the output, is that the even ones cause a break before any prints can occur.)

(Python has a special way that isn’t seen in other programming languages: it lets you use else with a for or while loop. But many people find this confusing, and it’s easy to type accidentally. You might prefer to use a separate variable to keep track of whether a divisor was found. Think carefully: how should it change when we find a divisor? When should we check the value, and what should we do with the result? Is there anywhere else we need to change it?)

(But in this case, it’s the perfect choice, so use it!)

True; this sort of situation is, as far as I can imagine, exactly why the feature exists. (Personally I prefer not writing explicit loops in the first place, but that’s a whole other pedagogic tangent.)