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