2013-12-23 56 views
-4
from math import * 

def p(): 
    for a in range (2, 100): ##for a in range 2 to 100 
     for y in range (2, a): ##for y in range 2, 100 
      x = 2*a+1   ##x has the following value 
      myprimelist = [] ##creating my empty list 

      if x > y: 
       while (x % y != 0): 
        myprimelist.append(x) ##append to list and continue with the same y until modulo is zero after which it reaches to else 
        y += 1 
        print (x,'nu se imparte egal la',y) 
        return [y] ##change the y 
       else: 
        y += 1 
        return [y] 
      else: 
       a += 1 
       return[a] 
     a += 1 
     return[a] 

    print (myprimelist); 

我想做一個函數,會告訴我從2到100所有素數,但由於某種原因循環停止,我不知道爲什麼。請幫忙。謝謝!這爲什麼停止在Python 33

+0

明白了:D那麼容易:P可以關閉請 – Andra

+0

這不是論壇回答問題後關閉。這裏提問者選擇一個他認爲有用的答案並接受它。此外,upvotes/downvotes有幫助/無益的答案。 –

+0

我已經搜索過它,但無法找到它 – Andra

回答

2

return意味着函數結束。每次遇到該函數都會停止執行。

0

它與python 3無關,它關於return語句。你可以嘗試下面的代碼,因爲它只檢查從1到sqrt(n),因爲它不會檢查大於sqrt(n)的數字。希望這可以幫助。

import math 
for num in range(1,101): 
    if all(num%i!=0 for i in range(2,int(math.sqrt(num))+1)): 
     print num