Codesters does not yet implement Python generators so lets pretend with our own little next() method. Check your console to see the first 30 primes. In class, I'll show what this looks like in the Spyder IDE.

class Primes: def __init__(self): self.candidate = 1 self._primes_so_far = [2] # first prime, only even prime def __iter__(self): return self def next(self): while True: self.candidate += 2 # check odds only from now on for prev in self._primes_so_far: if prev**2 > self.candidate: self._primes_so_far.append(self.candidate) return self._primes_so_far[-2] if not divmod(self.candidate, prev)[1]: # no remainder! break stage.set_background("volcano") sprite = codesters.Sprite("person11", 0, -100) # down to earth sprite.say("Do you know what prime numbers are? I do! Hit P.") p = Primes() # class based iterator the_primes = [p.next() for _ in range(300)] # n for number in the_primes: print(number)
  • Run Code
  • Show Console
  • Codesters How To (opens in a new tab)