6. is_prime


#1



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


code is OK, in both range versions,
but I do not know which one is correct?
many people here use 2,x range - differently than in instructions
please help me understand


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


#2

range() does not include its stop value, so when people read the instructions:

For each number n from 2 to x - 1, test if x is evenly divisible by n

they fail to realize (i don't blame them, made that mistake myself as well) that range stops at x-1

Both are correct, which is better? For this we can quote knut:

We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil


#3

In case it helps you understand range(), here's a link to the documentation.

Always feel free to experiment on your own in the console, too!

x = 10
print range(2, x) # [2, 3, 4, 5, 6, 7, 8, 9]
print range(2, x - 1) # [2, 3, 4, 5, 6, 7, 8]


#4

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