简体   繁体   English

Python:素数和inrange()

[英]Python: Prime numbers and the in range()

I am learning python and was looking at this problem: Python - Prime Number exercise Here are my questions: When n=2, the range will be (2,n), in the other words the range is between 2 and 2-1=1. 我正在学习python并正在研究此问题: Python-质数练习这是我的问题:当n = 2时,范围将是(2,n),换句话说,范围是2到2-1 = 1。

   for x in range(2, n):
      if n % x == 0:
        print("{} equals {} x {}".format(n, x, n // x))
        return False
   else:
      print(n, "is a prime number")
      return True

a. 一种。 Will it be 2%2? 会是2%2吗?

b. If the number is even, it will print 如果数字是偶数,它将打印

A equals B x C A等于B x C

will the loop break once the condition is true or it will finish the loop? 条件为真时,循环会中断吗?还是会结束循环?

c. C。 is the else outside the loop? 循环之外的其他东西吗? what if statement does it correspond? if语句对应什么? (i know it is the if n % x == 0: ) but howcome it is seems like it is outside the loop? (我知道这是if n % x == 0: :),但是看起来好像在循环之外呢? I tried to run it, and understand, but then I got confused. 我试图运行它,并且理解了,但是后来我感到困惑。

for .. else confusion 为了..否则混乱

You seem to be confused by else which is part of the for loop. 您似乎对for循环中的else感到困惑。

You are not the only one. 您不是唯一的一个。

In Python, for loop might have at the end else section, which is executed after all the loops are finished, unless there was break statement. 在Python中, for循环可能在else节的末尾,除非所有的break语句都在循环完成后执行。 Yes, it is not very intuitive. 是的,它不是很直观。

So you shall read the else section as last part of the for loop. 因此,您应将else部分作为for循环的最后一部分阅读。

def looptest(loops=5):
    for i in range(loops):
        print "i", i
        if i == 3:
            print "in if"
            return
    else:    
        print "in else of the loop"

and try it for loops == 5: 并尝试循环== 5:

>>> looptest(5)
i 0
i 1
i 2
i 3
in if

For number of loops 2 we do not expect return, we shall run through else of the loop: 对于循环2的数量,我们不期望返回,我们将遍历循环的else部分:

>>> looptest(2)
i 0
i 1
in else of the loop

Note, that return must be within function, trying return on console would result in error. 注意, return必须在函数内,尝试在控制台上返回将导致错误。

range(2, 2) == [] 范围(2,2)== []

Trying on Python console: 在Python控制台上尝试:

>>> range(2, 2)
[]

return 返回

return ends up current function or run in the whole module. return结束当前功能或在整个模块中运行。 So after return , no further code in the same part of your code is executed (with exceptions like try , finally , context managers etc, but this is not relevant to your code). 因此, return后,将不会再执行代码同一部分中的其他代码(特有tryfinally ,context manager等例外,但这与您的代码无关)。

a. 一种。 No. range(2,2) is an empty set in Python. No. range(2,2)在Python中是一个空集。

b. As soon as the condition is true, the function that contains the loop will return, and the loop will not finish. 条件为真时,包含循环的函数将返回,并且循环不会结束。 That's because the return call is one level down from the if statement. 这是因为return调用比if语句低一级。

c. C。 I'm pretty sure you want the else to correspond with the for . 我很确定您希望elsefor相对应。 Python's got this for...else syntax that executes the content of the else clause if the for loop terminates normally (ie without a break ). Python拥有此for ... else语法,如果for循环正常终止(即,不带break ),则执行else子句的内容。

In other words, I think you want this: 换句话说,我想你要这样:

for x in range(2, n):
        if n % x == 0:
            print("{} equals {} x {}".format(n, x, n // x))
            return False
else:
     print(n, "is a prime number")
     return True

EDIT: 编辑:

Sure, I can explain the whole loop. 当然,我可以解释整个循环。 The idea is this: for each number between two and n, check if that number is a factor of x. 这个想法是这样的:对于介于2和n之间的每个数字,检查该数字是否为x的因数。 If it is, then n isn't prime, and we kill the loop. 如果是,则n不是质数,我们终止循环。 However, if we make it all the way to the end of the loop, we know that n is prime, because it has no factors between 2 and n. 但是,如果一直进行到循环结束,就知道n是质数,因为它在2到n之间没有因数。 The else clause then kicks in, and prints that the number is prime. 然后,else子句插入,并打印该数字为素数。

Take a look at this function: 看一下这个函数:

def isPrime(n):
    for i in range(2, int(n**0.5) + 1):
        if n % i ==0:
            return False
    return True

Iterating through every possible option isn't necessarily the best option; 遍历每个可能的选项不一定是最好的选择。 keep in mind the range will never be more than the square root of the number. 请记住,范围永远不会超过数字的平方根。

Also worth noting, your output will only print the first set of factors. 同样值得注意的是,您的输出将仅显示第一组因子。

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

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