Python Yield
# Yield is just like return but with generator(?) objects instead of values
# Generators are special functions that have to be iterated to get the values
# To get the values the
# To get the values the objects has to be iterated
#Syntax yield expression
# #Sample yield function
# def demoyield():
# yield "Welcom to AMET - Pioneer in Maritime Education"
#
# out = demoyield()
# print(out)
# #<generator object demoyield at 0x000002802AC5DA50>
# # iterate to get the value in the above object
# #Generators are functions that return an iterable generator object. The values from the generator object are fetched one at a time instead of the full list together and hence to get the actual values you can use a for-loop, using next() or list() method
# for i in out:
#. print(i)
# Example 2
# def gen():
# yield 'G'
#. yield 'A'
# yield 'N'
# yield 'D'
# yield 'H'
# yield 'I'
# yield ' '
# yield 'M'
# yield 'A'
# yield 'H'
# yield 'A'
# yield 'N'
#
# demo = gen()
#
# for i in demo:
#. print(i)
#
#example 3 difference between normal function and generator function
#Normal
def normalfun():
return 'Hello Zoox Robo Taxi to Universe - normal function'
def genfun():
yield "'Hello Zoox Robo Taxi to Universe - generator function"
print(normalfun())
print(genfun())
# Hello Zoox Robo Taxi to Universe - normal function
#until it prints the whole string normalfun()wont stop
# <generator object genfun at 0x00000298E53AD900>
#but gen iterates so we can use the generator obhject to get the values and also , 'pause' and 'resume'
print(next(genfun()))
#Note next function
print(list(genfun()))
No comments:
Post a Comment