Open In App

Python Yield And Return In Same Function

Last Updated : 05 Feb, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

Python, a versatile and powerful programming language, offers developers various tools and features to enhance code readability and efficiency. One such feature is the combination of yield and return statements within the same function. In this article, we will explore some commonly used methods where these two statements work together, providing a flexible and dynamic approach to programming.

Understanding Yield and Return

Before delving into the examples, let’s briefly understand the difference between yield and return statements in Python functions.

  • yield Statement:
    • Used to produce a sequence of values for iteration.
    • Pauses the function’s state, allowing it to resume from where it left off when the next value is requested.
    • Preserves the local state of the function, making it suitable for creating generators.
  • return Statement:
    • Used to terminate the function and return a value to the caller.
    • After a return the statement is encountered, the function is exited, and no further code in the function is executed.

Python Yield And Return In the Same Function

Below, are the examples of Python Yield And Return In the Same Function.

  • Generator Function
  • Filtering Generator
  • Concatenate Two Generators
  • Generator with Exception Handling

Generator Function

In this example, the number_generator function produces a generator that yields numbers from 0 to n-1, and after the loop, it prints a message indicating the total number of generated values. In the example usage, the generator is invoked with number_generator(5).

Python3




def number_generator(n):
    for i in range(n):
        yield i
    return f"Generated {n} numbers."
 
# Example usage:
for number in number_generator(5):
    print(number)


Output

0
1
2
3
4


Filtering Generator Using Yield And Return In Same Function

In this example, the filter_even_numbers function generates a sequence of even numbers from the input list, and after the loop, it prints a success message. In the example usage, the function is applied to the list [1, 2, 3, 4, 5, 6], and the even numbers are printed using a for loop.

Python3




def filter_even_numbers(numbers):
    for num in numbers:
        if num % 2 == 0:
            yield num
    return "Even numbers filtered successfully."
 
# Example usage:
for even_number in filter_even_numbers([1, 2, 3, 4, 5, 6]):
    print(even_number)


Output

2
4
6


Concatenate Two Generators Using Yield And Return In Same Function

In this example, the concatenate_generators function sequentially yields elements from two input generators (gen1 and gen2) and prints a success message after the concatenation. In the example usage, the function is applied to generators representing ranges, and the result is printed/

Python3




def concatenate_generators(gen1, gen2):
    yield from gen1
    yield from gen2
    return "Generators concatenated successfully."
 
# Example usage:
for result in concatenate_generators(range(3), range(3, 6)):
    print(result)


Output

0
1
2
3
4
5


Exception Handling Using Yield And Return In Same Function

In this example, the safe_divide generator function attempts to calculate the result of dividing dividend by divisor and yields the result. If a ZeroDivisionError occurs, it returns the message “Cannot divide by zero.” In the example usage, the generator is applied to divide 10 by 2.

Python3




def safe_divide(dividend, divisor):
    try:
        result = dividend / divisor
        yield result
    except ZeroDivisionError:
       return "Cannot divide by zero."
 
# Example usage:
for division_result in safe_divide(10, 2):
    print(division_result)


Output

5.0


Conclusion

In conclusion , the combination of yield and return within the same function allows developers to create versatile and powerful code structures in Python. Whether it’s generating sequences, filtering data, or handling exceptions, this feature provides a dynamic and elegant solution. By leveraging these techniques, developers can write more readable, modular, and efficient code.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads