The program creates a generator

Telemarketing List helps companies reach the right prospects with targeted and reliable telemarketing data.
Post Reply
aminaas1576
Posts: 565
Joined: Mon Dec 23, 2024 3:18 am

The program creates a generator

Post by aminaas1576 »

Let's look at another example where a generator function produces an infinitely long sequence of numbers. def halfs(next_half = 0.0): while True: yield next_half next_half += 0.5 The function returns the numbers 0, 0.5, 1, 1.5, etc. ad infinitum. Let's use this function to create a list of numbers that satisfy the condition n < 3: res = [] for i in halves(): res. append(i) if i >= 2.0: break print(res) > [0.0, 0.5, 1.0, 1.5, 2.0] Each time the halfs function is called, it returns a generator that increases the current value by 0.5.

The value can not only be returned, but also passed to the generator using the send() method. def triple_numbers(): while True: n = yield yield n * 3 g = triple_number() next(g) print(g.send(10)) next(g) print(g.send(50)) > 10 50 You can handle exceptions using the throw() method: def triple_numbers(num): while True: num *= 3 yield num australia email list gen = triple_numbers(3) for i in gen: if i > 100: gen.throw(Exception("Error!")) print(i) > 9 27 81 Exception: Error! that infinitely multiplies the user-supplied number by 3 until it exceeds 100, which will raise an Error exception.

The close() method can be used to force the generator function to stop executing: def triple_numbers(num): while True: num *= 3 yield num gen = triple_numbers(3) for i in gen: if i > 100: gen.close() print(i) > 9 27 81 243 The call to close() throws a GeneratorExit exception at the point of the last yield call. There is no need to catch this exception, because close() does this automatically. No error message is generated, and the last print(i) statement in the for loop executes successfully (printing the number 243). Generators in Python: How to Use Them You can learn how to use generators in real-world practical tasks in DevEducation courses . Python programmers often choose this programming language as their first language because it has a minimalist and intuitive syntax, is simple, multifunctional, versatile, and in demand in the market. Mastering Python from scratch to junior level can take no more than a year if you have the desire. Courses will help to significantly speed up this process and provide practical experience in solving specific real problems, which cannot be found on the pages of reference books and self-study guides.
Post Reply