Jun Min Kim
Jun Min Kim

Reputation: 275

Difference between looping through a list and looping through objects one by one?

I started learning Python through Codecademy and pondered upon an exercise that required me to write a program that determined if a number was a prime number or not.

When my original code did not work, I did some research and found code that did work. I looked through both of them and it looked like there was no difference between them except the fact I had used for loops to loop through a list when the working code used a while loop to loop through the objects one by one, so I was wondering if that was indeed the case (and if so, what difference it would make) or if my code had a logical error.

Sorry for the block of text, below I will provide both my code (that did not work) and the answer code (which did work)

My code here:

    def primer(x):
        if x < 2:
            return False

        elif x > 2:
            for n in range(2, x):
                if x % n == 0:
                    return False
                else:
                    return True
        else: 
            return True

and the code that did work here:

    def is_prime(x):
        if x < 2:
            return False

        elif x > 2:
            n = 2
            while n < x:
                if x % n == 0:
                    return False
                n += 1
            else:
                return True
        else:
            return True

Thank you for even taking the time to read this, and have a nice day.

Upvotes: 1

Views: 57

Answers (1)

Selcuk
Selcuk

Reputation: 59238

You immediately return True when you find that the number is not divisible, before trying all the possible divisors. Remove the else block:

def primer(x):
    if x < 2:
        return False

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

Upvotes: 2

Related Questions