简体   繁体   中英

how to print sum of primes in a list in python?

How do I print sum of primes in a list in Python?

I'm a new to Python, therefore I might be making a terrible mistake.

Please help out.

def prime(n):

    i = 2
    c = 0
    for i in range(1,n+1):
        if(n%i == 0):
            c = c+1
    if(c == 2):
        return True
    else:
        return False


def sumprimes(l1):

    l1 = []
    l = len(l1)
    i = 0
    sum = 0
    for i in range(0,l):
        if(prime(l1[i]) is True):
            sum = sum +l1[i]
print(sum)

l1 = [3,4,5,6]

print(sumprimes(l1))

Output should be equal to 8.

def prime(n):

    i = 2
    c = 0
    for i in range(1,n+1):
        if(n%i == 0):
            c = c+1
    if(c == 2):
        return True
    else:
        return False


def sumprimes(l1):

    sum=0
    for x in l1:
        if prime(x):
            sum += x
    return sum

l1 = [3,4,5,6]

print(sumprimes(l1))

Use the above code. You need to use the return statement to print the result of a function. And there is no need for your range() loop, there is a more elegant way to do this in python, use a for loop over all elements of the list.

You can do it using below code too.

lst = [1,2,5,7,9,10,12]

def isPrime(x):
    if x == 1:
        return False
    for i in range(2,x-1):
        if x%i == 0:
            return False
    return True


def getPrimeSum(l):
    l = [i for i in l if isPrime(i)]
    return sum(l)

print(getPrimeSum(lst))
#Check and add into the list of primeval numbers (all primeval number under a specific number)
H = int(input("What the maxium number?: "))
RangeFinding = list(range(3, H+1))
import math
Prime = [2]
for a in RangeFinding:
  x = True
  y = 2
  while x:
    NCanA = math.floor(math.sqrt(a))
    if a %y == 0:
      print(f'{a} is not prime')
      x = False
    else:
      if y > NCanA:
        print(f'{a} is prime')
        Prime.append(a)
        x = False
      else:
        y = y + 1
        x = True
print(Prime)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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