Python Generators & Decorators Explained

day 15 Generator 🔹 Generator in Python A Generator is a special type of function that allows you to generate values one at a time instead of returning all values at once. Normally, when we use return, a function ends after returning one value. But using the yield keyword, a generator can pause its execution and continue later, producing multiple values over time. Why use Generators? ✔ Saves memory ✔ Handles large datasets efficiently ✔ Generates values only when needed (lazy evaluation) Example def number_generator(): yield 1 yield 2 yield 3 for num in number_generator(): print(num) How it works 1️⃣ Function starts execution 2️⃣ yield returns a value 3️⃣ Function pauses its state 4️⃣ When called again, it continues from where it stopped Decorator in Python A Decorator is used to modify or extend the behavior of a function without changing its original code. In simple terms, a decorator wraps another function and adds extra functionality. Why use Decorators? ✔ Code reusability ✔ Clean and maintainable code ✔ Add logging, authentication, timing, etc. Example def my_decorator(func): def wrapper(): print("Before function execution") func() print("After function execution") return wrapper @my_decorator def say_hello(): print("Hello!") say_hello() Decorators are widely used in frameworks like Flask, Django, and FastAPI 15 challenge completed i have covered all topics in python more information follow Prem chandar #Python #PythonProgramming #MachineLearning #DataScience #SoftwareDevelopment #Coding #DeveloperLife #AI #TechLearning #social media #network #share #support

To view or add a comment, sign in

Explore content categories