简体   繁体   English

python 中给定范围内的素数,范围()问题,

[英]Prime number in a given range in python, problem with range(),

This program prints prime no between 1-20, i have tried to grasp the working of(for loop,range & else associated with for) in this program该程序打印 1-20 之间的素数,我试图掌握该程序中(for 循环,范围和其他与 for 关联)的工作

def isPrime(num):
    for i in range(2,num):
        if num%i==0:
            return False
        #else:
            #return True
    else:
        return True

#below is driver program        
for i in range(1, 20):
    if isPrime(i + 1):
        print(i + 1, end="\n")
print()

1.in this program put num//2 instead of num in range() result is diff (prints 4 as prime)why? 1.在这个程序中,将 num//2 而不是 num in range()结果是差异(打印 4 作为素数)为什么?

  1. when 2 is sent to isprime() , it doesn't even enter for loop,it is not being checked by if conditions but outputs 2 as a prime by the else block associated with for.当 2 被发送到isprime()时,它甚至不会进入 for 循环,它不会被 if 条件检查,而是由与 for 关联的 else 块输出 2 作为素数。 why?how?为什么?怎么? i think because of range(2,num) ,2 is passed as num.我认为由于range(2,num) ,2 作为 num 传递。

Can someone Explain??有人能解释一下吗??

The issue is that range(2,n) is all numbers 2, 3, ..., n-1.问题是range(2,n)是所有数字 2, 3, ..., n-1。 So change your for loop to:因此,将您的for循环更改为:

for i in range(2,num+1):

As is, when 2 is passed in, the range will be empty.照原样,当传入 2 时,范围将为空。

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

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