Return to site

Program to print list of all prime numbers between 1 and 100

broken image

We'll leave the printing to the caller: def is_prime(N, a=3):Įlif N N: # tried all divisors to sqrt, must be primeĮlif (N % a) = 0: # divides evenly, not a primeĮlse: # can't tell yet, recursively try the next (odd) divisor In this case is_prime() looks like a boolean function so it should return True or False. Your function sometimes returns something and sometimes returns nothing - it should be either all one or the other, not both. That prime variable will not be 'shared' across invocations, it will just create a new prime every time.ĮDIT: Didn't realize you wanted the function to just print out the prime if it's a prime, changed the code accordingly. Maybe your confusion comes from a misunderstanding of scopes in Python. I think you have a misunderstanding of how recursion works, you're assigning this prime variable in the body of the function, but never doing anything with it.

broken image

So if you run the above function like so, you should get the right output: print(is_prime(2, 7)) => True You didn't give any examples of calling this function, but I assume it's always called with a being 2, since any other value wouldn't make sense.

broken image

Your solution is close, with just a few changes needed to make it work.

broken image