简体   繁体   English

Python if语句不带==运算符

[英]Python if statement without == operator

Can someone explain to me how this function works? 有人可以向我解释此功能的工作原理吗? I don't get how the for loop keeps going while there is return False after the if statement, which is also unclear to me. 我不知道在if语句之后return False时,for循环如何继续进行,这对我也不清楚。

def IsPrime(n):
    for x in range(2, int(n/2+1)):
        if not n % x:
            return False;
    return True

I don't understand what is happening in line 3 of this code. 我不明白此代码第3行中发生了什么。

In short: the if fires when n is dividable by x . 简而言之:n可被x 整除时, if会触发。

Background : 背景

If you write something with: 如果您使用以下方式写东西:

if <expr>:
    pass

The not keyword also evaluates the truthiness , and in case the truthiness is True of the expression, then not expression is False and vice versa. not关键字还会计算真实性 ,如果表达式的真实性为True ,则not expressionFalse ,反之亦然。

Python checks the truthiness of the <expr> . Python检查<expr>真实性 The truthiness is a boolean value that is associated with objects. 真实性是与对象关联的布尔值。

True and False have as truthiness respectively True and False , and None has truthiness False (so we can check if someobject usually to do an implicit None check). TrueFalse具有真实性,分别为TrueFalseNone具有真实性False (因此,我们可以检查某个对象if someobject通常执行隐式None检查)。

Collections like list s, set s, dict s, tuple s, etc. usually have truthiness True if and only if these collections contain at least one element. 喜欢收藏list S, set S, dict S, tuple S等通常有感实性True当且当这些集合至少包含一个元素。 So empty collections have truthiness False . 因此,空集合的真实性为False What these collections contain is of no importance for the truthiness of the collection itself. 这些收藏所包含的内容对于收藏本身的真实性并不重要。

Then there are also numerical types. 然后还有数字类型。 Usually a number has truthiness False if and only if it is equal to zero, so negative and strictly positive numbers have truthiness True . 通常,当且仅当它等于零时,它的真性为False ,因此负数和严格为正数的True

Generic objects have by default truthiness True , but you can override the __bool__ magic function to return a different truthiness, or if you override __len__ (and not __bool__ ), it will check if __len__ is greater than zero. 通用对象都默认感实性True ,但是你可以重写__bool__魔术函数返回一个不同的感实性,或者如果重写__len__ (而不是__bool__ ),它会检查是否__len__大于零。

So if n and x are integers, then we calculate n % x , this thus performs a modulo check, and n % x is zero if and only if n is dividable by x . 因此,如果nx为整数,则我们计算n % x ,这将执行取检查,并且当且仅当n可除以xn % x才为零。

Now the not operator will thus evaluate the truthiness. 现在, not操作员将因此评估真实性。 In case n is dividable by x , then not n % x is True , otherwise not n % x is False . 如果n可被x整除,则not n % x不是True ,否则not n % x不是False

So the if is fired if n is dividable by x . 因此, if n可被x整除,则会触发if。 The prime test thus checks if n is dividable by all numbers between 2 and n/2+1 , and if not, it returns True , from the moment one is dividable, it returns False . 因此,素数检验检查n是否可被2n/2+1之间的所有数字可除,如果不是,则返回True ,从可被分割的那一刻起,它返回False

We can however speed up the calculations by iterating up to the square root of n , and make hops of two: 但是,我们可以通过迭代到n 平方根来加快计算速度,并跳两步:

from math import sqrt

def IsPrime(n):
    if not n % 2:
        return False
    for x in range(3, int(sqrt(n)), 2):
        if not n % x:
            return False
    return True

What follows after if , will be casted to type bool , ie even though you put an integer in, python will have to cast it to bool , because if can only branch on the boolean values True or False . if之后的内容将被强制转换为bool类型,即,即使您输入了整数,python也将不得不将其boolbool ,因为if仅可以分支到布尔值TrueFalse
Now python evaluates all numbers except 0 to True in the bool(number) function. 现在,python计算bool(number)函数中除0到True以外的所有数字。 So basically if not n%x is the same thing as if not ((n%x) != 0) . 因此,基本上, if not n%x则与if not ((n%x) != 0)

Example x=2 : code inside the loop will be executed for even values of n . 示例x=2 :循环内的代码将针对n偶数执行。

在第3行,你把n通过之间的整数2 to n/2 ,现在让我们来看看if not n%x:这里如果x分歧ñ完全然后n%x返回0这被解释为False 。现在notFalseTrue因此条件评估为真,你的IsPrime(n)函数返回False 。所以,任何数量的n具有之间的因子2n-1或更精确地之间的2 and n/2是不是质数,那么你的函数返回否,否则您的函数将评估为True

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

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