問(wèn)題描述
我設(shè)法使用以下方法創(chuàng)建了給定范圍內(nèi)的素?cái)?shù)列表:
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=int(np.sqrt(a)) + 1
for i in range(2,maxInt):
if (a%i==0):
break
else:
print (a)
我現(xiàn)在想找到范圍內(nèi)所有素?cái)?shù)的總和,所以我就把它寫(xiě)下來(lái)
I want to now find the sum of all of the prime numbers in the range so I just put down
print (sum(a))
但在嘗試這樣做時(shí),我得到以下回溯:
But when trying to do that, I get the following traceback:
Traceback (most recent call last):
File "C:/Users/Jason/PycharmProjects/stackidiots/scipuy.py", line 11, in <module>
print(sum(a))
TypeError: 'int' object is not iterable
推薦答案
在您的情況下,a
是循環(huán)中使用的整數(shù)變量,不是 可迭代的.
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 in range(2,num+1):
maxInt= int(np.sqrt(a)) + 1
for i in range(2,maxInt):
if (a%i==0):
break
else:
primes.append(a)
print(sum(primes))
因此,如果我們只是將它們附加到列表中而不是打印它們,當(dāng)獲取列表 primes
的 sum
時(shí),我們會(huì)得到以下輸出.
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: 43
281
這篇關(guān)于如何在 Python 3.5 中找到給定范圍內(nèi)的素?cái)?shù)總和?的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!