import random class PasswordGenerator: def __init__(self, length, count, charset = list("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")): if count < 0: raise ValueError("Count must be non-negative") if length < 0: raise ValueError("Length must be non-negative") if not charset: raise ValueError("Charset must not be empty") self.length = length self.count = count self.charset = charset def __iter__(self): return self def __next__(self): if self.count == 0: raise StopIteration self.count -= 1 return "".join(random.choices(self.charset, k=self.length)) if __name__ == "__main__": generator = PasswordGenerator(10, count=10) print("for loop") for password in generator: print(password) print() print("charset = 1234") generator = PasswordGenerator(10, count=3, charset=list("1234")) for password in generator: print(password) print() generator = PasswordGenerator(10, count=2) print("__next__(), generator count = 2") print(generator.__next__()) print(generator.__next__()) print("what happens when you call __next__ too many times:") # exception # b print(generator.__next__())