The yield
and return
statements are used to output expressions in functions.
A function pauses at a yield
statement and resumes at the same place upon re-execution. A function fully exits at the encounter of a return
statement without saving the function’s state.
The syntax for the yield
statement is given below:
yield expression
We’ll use the yield
statement in the code below:
# Defining the generator function def test_yields(): yield 'Item 1' yield 'Item 2' # Assigning the generator function iter_object = test_yields() # Each time the generator function is invoked it returns a different item print(next(iter_object)) print(next(iter_object)) # Printing out the variable iter_object returns a generator object print(iter_object)
test_yields()
.test_yields()
function yields two items; item 1
and item 2
.test_yields()
to the variable iter_object
.next()
test_yields()
.iter_object
without the next()
function to return a generator object.A function with a yield
statement (generator function) returns a generator object. A generator is a type of iterator. Each item in the generator object can be retrieved in sequence by using the next()
function.
The syntax for the return
statement is given below:
return expression
We’ll use the return
statement in the code below:
# Defining the function def test_return(): return 'Item 1' return 'Item 2' # Function exit at the first return statement print(test_return()) print(test_return())
test_return()
.test_return()
function returns two items; item 1
and item 2
.test_return()
function twice and print out the result.The test_return()
exits immediately after the first return
statement. It only returns item 1
, even after re-execution, because the previous state of test_return()
is not saved.
RELATED TAGS
CONTRIBUTOR
View all Courses