程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式師世界 >> 編程語言 >  >> 更多編程語言 >> Python

Python judging prime number (prime number): understanding and example application of for else loop

編輯:Python

for-else loop

It is mainly used to judge whether the cycle is incomplete ( That is, whether it is interrupted in the middle ), If the cycle runs completely ( Not interrupted halfway ), execute else Statement content , Otherwise, do not execute ,
Common ways to jump out of the loop :break、continue、return( Within the function )


for-else The logic of loops in judging prime numbers

If it can be divided ( Not primes ),break Jump out of the present for loop , Do nothing ; If it's not divisible ( Prime number ),for After iteration, there are no books break Out of the loop , perform else sentence , Add this prime number to the list


Example

a=[3,1,12,5,14,8,7,2,5,3,2,6,7,2,3,8,5]# Find the primes and sum them 
b=[]
for i in a:
if i>1:
for j in range(2,i//2+1):
if i%j==0:
break
else:
b.append(i)
print(b)
print(sum(b))

Of course, you can also use the method of defining functions

def iszhi(n):
if n>1:
for i in range(2,n//2+1):
if n%i==0:
return False
else:
return True
a=[3,1,12,5,14,8,7,2,5,3,2,6,7,2,3,8,5]
b=[]
for j in a:
if iszhi(j)==True:
b.append(j)
print(b)
print(sum(b))

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式師世界 All Rights Reserved