In Python, the
return keywords are both used to return values from a function, but they have different purposes and behaviors.
return is a keyword that is used to exit a function and return a value to the caller. When you use
return, the function is terminated and no further code in the function is executed. Here's an example:
def add_numbers(x, y): result = x + y return result sum = add_numbers(2, 3) print(sum) # Output: 5
add_numbers function returns the result of the addition operation using
return. This value is then stored in the variable
sum and printed to the console.
yield is also used to return a value from a function, but in a different way. When a function contains a
yield statement, it becomes a generator function, which means that it can be used to create an iterator. Here's an example:
def generate_numbers(n): for i in range(n): yield i numbers = generate_numbers(5) for num in numbers: print(num)
generate_numbers function uses a
yield statement to return each number from the range
n-1. When the
generate_numbers function is called, it returns a generator object which can be used to iterate over the values using a
for loop. In this example, the values
0 1 2 3 4 are printed to the console.
So in summary,
return is used to return a single value and exit the function, while
yield is used to return a sequence of values one at a time and keep the function running.