-2

I am trying to write a program that is constantly generating and prime numbers. So you would start it then the prime numbers are saved to a text file or as a string. So far I have got this code but don't know how to make it work continuously.

def primenumbers():
    j = 2
    chk = 1
    f = open("primes.txt", "w")
    primes = []
    notprimes = []
    ask = input("how many primes? ")
    while len(primes) < int(ask):
        k = 2
        while not(k==j) and not(j%k==0):
            k = k + 1
        if k == j:
            primes.append(j)
            f.write(str(j)+"\n")
        else:
            notprimes.append(j)
        if len(primes) >= 1000*chk:
            chk = chk + 1
            print("There have been " + str(len(primes)) + " primes counted so far")
        j = j + 1
    print("Primes written to file 'primes.txt', " + str(len(primes)) + " written")
    f.close
    return(" ")
quamrana
  • 37,849
  • 12
  • 53
  • 71
MagikCow
  • 863
  • 8
  • 13

1 Answers1

3

In your script, add this at the bottom (not indented)

if __name__ == '__main__':
    while(True):
        primenumbers()

So the function will keep being called

Useful link:
What does if __name__ == "__main__": do?

Community
  • 1
  • 1
Tim
  • 41,901
  • 18
  • 127
  • 145