Normal function in Python
Normal function performs a specific task and can be called from other parts of the program. Also normal function return a single value and terminate the session.
Python3
# generator function named square() def square(): number = 2 # Create infinite loop while True : # Yield the current value of 'number' yield number # Calculate the square of 'number' and update its value number * = number # Define a function to retrieve the next square from the generator. def get_next_square(): global number_generator try : # Try to get the next square from the existing generator return next (number_generator) except NameError: # If 'number_generator' is not defined , initialize it number_generator = square() # Return the first square from the newly created generator. return next (number_generator) # function call to retrieve the next square and print it. print (get_next_square()) # Output: 2 print (get_next_square()) # Output: 4 |
2 4
As you can see, the generator function uses the yield keyword instead of return and generates values as they are needed, rather than creating a list of all values at once.
Difference between Generator and Normal Function
Normal functions in Python are used for traditional computation tasks, with execution proceeding from start to finish, typically returning a single result. On the other hand, generator functions employ the `yield` statement to produce values lazily, preserving their state across multiple calls. This allows generators to efficiently handle large datasets or infinite sequences by yielding values one at a time and pausing execution when necessary, making them a valuable tool for memory-efficient and iterative tasks. In this article, we’ll look into Python generator functions and normal function differences i.e. how different are their syntax, how is data handled, and practical applications.