這個節目想找到1000張素數,並將它們打包到一個列表功能保持做同樣的事情
下面的代碼:
num = raw_input('enter a starting point')
primes = [2]
num = int(num)
def prime_count(num):
if num % 2 == 0: #supposed to check if the number is divided by 2 evenly
num = num +1 #if it is, then add 1 to that number and check again
return num
elif num % num == 0:
primes.append(num) #supposed to add that prime to a list
num = num + 1 #add 1 and check again
return num
while len(primes) <= 999:
prime_count(num)
那麼,當我運行它實際發生: 它要求我的raw_input然後去根據不同的東西是什麼我選擇爲輸入:
- 如果讓我選擇一個素數,假設3,它運行,並增加了3秒999的列表,而不是將它添加只有一個的T IME和正在進行嘗試4
- 如果讓我選擇一個非黃金,假設4,它只是打破了,在那之後我甚至不能打印出清單
我到底做錯了什麼?
更新: 我固定它,但是當我有了這個,我發現了一個錯誤運行(類型錯誤:不支持的操作數類型爲%:「NoneType」和「INT」)
number = raw_input('enter a starting point')
primes = [2]
number = int(number)
def prime_count(x):
if x % 2 == 0: #supposed to check if the number is divided by 2 evenly
number = x +1 #if it is, then add 1 to that number and check again
return number
else:
for i in range(3, x-1):
if x % i == 0:
primes.append(x) #supposed to add that prime to a list
number = x + 1 #add 1 and check again
return number
while len(primes) <= 999:
number = prime_count(number)
你似乎不理解局部變量和全局變量之間的區別,或者函數參數和返回值的工作方式。爲了幫助,我建議你重命名'prime_count'之外的所有變量。 –
您需要了解Python中的範圍規則。 'num'被視爲'prime_count'中的局部變量。無論如何,這裏用戶輸入的意義何在? –