Generator function in Python with Exception

''' Generator function with Exception minimum 1 argument, maximum 3 arguments 1 Argument: generator(25) -> 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 2 Argument: generator(1,25) -> 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 3 Argument: generator(1,25,4) -> 1 5 9 13 17 21 25 ''' #!/usr/bin/env python3 def generator(*args): numargs = len(args) start = 0 step = 1 if numargs < 1: raise TypeError(f'Minimum argument is 1, got {numargs}') elif numargs == 1: (stop) = args[0] elif numargs == 2: (start, stop) = args elif numargs == 3: (start, stop, step) = args else: raise TypeError(f'Maximum arguments is 3, got {numargs}') result = start while result <= stop: yield result result += step def main(): try: for x in generator(25) print(x, end=' ') print() except TypeError as e: print(f'Error: {e}') if __name__ == '__main__': main()
Python Generator with Exception

Be the first to comment

You can use [html][/html], [css][/css], [php][/php] and more to embed the code. Urls are automatically hyperlinked. Line breaks and paragraphs are automatically generated.