How Do I Find The Sum Of Prime Numbers In A Given Range In Python 3.5?
I managed to create a list of prime numbers in a given range using this: import numpy as np    num = int(input('Enter a number: '))    for a in range(2,num+1):            maxInt=in
Solution 1:
In your case, a is an integer variable being used in your loop, not an iterable.
import numpy as np
num = int(input("Enter a number: "))
primes = []
for a inrange(2,num+1):
  maxInt= int(np.sqrt(a)) + 1for i inrange(2,maxInt):
    if (a%i==0):
      breakelse:
    primes.append(a)
print(sum(primes))
So if we just append them to a list as we go instead of printing them, we get the following output when taking the sum of the list primes.
Enter a number: 43281Solution 2:
If you want to use sum, you could make a generator function, yielding each a in the loop so you have an iterable to call sum on:
num = int(input("Enter a number: "))
defsum_range(num):
    for a inrange(2, num + 1):
        maxInt = int(a **.5) + 1for i inrange(2, maxInt):
            if a % i == 0:
                breakelse:
            yield a
print(sum(sum_range(num)))
Solution 3:
Sum them inside the loop
import numpy as np  
num = int(input("Enter a number: "))  
result=0for a inrange(2,num+1):         
  maxInt=int(np.sqrt(a)) + 1for i inrange(2,maxInt):
    if (a%i==0):  
      breakelse: 
      print (a)
      result+=a
print(result)
Post a Comment for "How Do I Find The Sum Of Prime Numbers In A Given Range In Python 3.5?"