Is_prime - I think I understand why the code works. Can someone check?


#1

https://www.codecademy.com/courses/python-intermediate-en-rCQKw/0/6?curriculum_id=4f89dab3d788890003000096#

I think I understand why this code works, and I want to explain it in words to see if my line of thinking is correct. May someone validate whether or not my line of thinking is correct?

def is_prime(x):
    if x < 2:
        return False
    elif x == 2:
        return True
    else:
        for n in range(2, x - 1):
            if x % n == 0:
                return False
        return True

For instance, let's say x is equal to 21. I know 21 is not a prime number. It checks to see if it's less than 2, which 21 is not, so it moves on. 21 is not equal to 2, so it moves on. Then, it enters the for loop, starting with 21 modulo 2, which is not equal to zero. Next, does it automatically move n up to 3, and check to see if 21 modulo 3 is equal to zero (which it is, so it's not a prime number), as opposed to automatically moving on to "return True"? It will iterate through all of the possible values of n before moving on to the True statement, correct?


#2

yep, your look is correct. and when you have 21 modulo 3, which makes return false, the function ends (causing the loop to break)

The rest of your logic is correct

if the number is a prime number (13) it cycles through the loop. Because the loop ends, true will be returned


#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.