繁体   English   中英

试图理解这个简单的python代码

[英]Trying to understand this simple python code

我正在阅读Jeff Knupp的博客,我偶然发现了这个简单的小脚本:


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))

(注意:我在开头添加了导入数学。你可以在这里看到原文: http//www.jeffknupp.com/blog/2013/04/07/improve-your-python-yield-and-generators-explained /

这一切都很简单,我得到了大部分,但我不确定他使用范围功能会发生什么。 我没有用过这种方式,或者看过其他人用这种方式,但我是初学者。 范围函数具有三个参数意味着什么,以及如何完成对完整性的测试?

另外(并且如果这是一个愚蠢的问题而道歉),但是最后一次'返回False'声明。 那就是如果一个数字被传递给小于一的函数(因此不能成为素数),该函数甚至不会浪费时间来评估这个数字,对吗?

第三是步骤。 它遍历每个奇数小于或等于输入的平方根(3,5,7等)。

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))

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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