简体   繁体   中英

Trying to understand this simple python code

I was reading Jeff Knupp's blog and I came across this easy little script:


import math

def is_prime(n):
    if n > 1:
        if n == 2:
            return True
        if n % 2 == 0:
            return False
        for current in range(3, int(math.sqrt(n) + 1), 2):
            if n % current == 0:
                return False
        return True
    return False

print(is_prime(17))

(note: I added the import math at the beginning. You can see the original here: http://www.jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained/ )

This is all pretty straightforward and I get the majority of it, but I'm not sure what's going on with his use of the range function. I haven't ever used it this way or seen anyone else use it this way, but then I'm a beginner. What does it mean for the range function to have three parameters, and how does this accomplish testing for primeness?

Also (and apologies if this is a stupid question), but the very last 'return False' statement. That is there so that if a number is passed to the function that is less than one (and thus not able to be prime), the function won't even waste its time evaluating that number, right?

The third is the step. It iterates through every odd number less than or equal to the square root of the input (3, 5, 7, etc.).

import math #import math module

def is_prime(n): #define is_prime function  and assign variable n to its argument (n = 17 in this example).
    if n > 1: #check if n (its argument) is greater than one, if so, continue; else return False (this is the last return in the function).
        if n == 2: #check if n equals 2, it so return True and exit.
            return True
        if n % 2 == 0: #check if the remainder of n divided by two equas 0, if so, return False (is not prime) and exit. 
            return False
        for current in range(3, int(math.sqrt(n) + 1), 2): #use range function to generate a sequence starting with value 3 up to, but not including, the truncated value of the square root of n, plus 1. Once you have this secuence give me every other number ( 3, 5, 7, etc)     
            if n % current == 0: #Check every value from the above secuence and if the remainder of n divided by that value is 0, return False (it's not prime)
                return False
        return True #if not number in the secuence divided n with a zero remainder then n is prime, return True and exit.  
    return False

print(is_prime(17))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM