0

I've been plugging away on the Codecademy python course and I had a solution that worked. However, during the verification process, I added an extra bit of code that would print the current state the for loop is in. When I execute the code, however, it seems to go through one iteration before quitting, which I know is not the case. The following is my code:

def is_prime(x):
    if x < 2:
        return False
    if x == 2:
        return True
    if x == 3:
        return True
    else:
        for n in range(2,x-1):
            if x % n == 0:
                print "Current value is %d." %n
                return False
        return True

How can I make it print a value each "n" value when the number is going through the loop?

1
  • 2
    move the print directly under the for loop.
    – shuttle87
    Jun 15, 2015 at 4:36

3 Answers 3

1

Your issue is that you are only printing when x % n == 0 , and then right away you are returning 'False' , hence its only printing once.

You need to move the print statement to just below for loop , something like -

def is_prime(x):
    if x < 2:
        return False
    if x == 2:
        return True
    if x == 3:
        return True
    else:
        for n in range(2,x-1):
            print "Current value is %d." %n
            if x % n == 0:
                return False
        return True
1
  • That did the trick. And in hindsight I can see how the "if" statement may throw a wrench in the desired process. Thanks for the help!
    – ozbot87
    Jun 15, 2015 at 21:59
1

Try this one. I'm using Fermat's little theorem :

def is_prime(x):
  if x > 1 and ((2)**x-(2))%x == 0:
    return True
  return False
0
def is_prime(x):
    if x < 2:
        return False

    else:
        for n in range(2,x - 1):
            if x % n == 0:
                return False


return True
1
  • Welcome to Stack Overflow! While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion. Please also try not to crowd your code with explanatory comments, this reduces the readability of both the code and the explanations! May 5, 2017 at 3:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.