Home » Python

yield keyword with example in Python

Python yield keyword: Here, we are going to learn about the yield keyword with example.
Submitted by IncludeHelp, on April 16, 2019

Python yield keyword

yield is a keyword (case-sensitive) in python, it is used to suspend the execution of a function and returns the value, if next time function calls, it resumes the function execution from the next statement where last execution was suspended.

Note: return keyword and yield keywords returns the value to the called function, but the return statement terminates the execution of the function, while yield statement just suspends the execution of the programs.

Syntax of yield keyword

    def function_name():
	    statement(s):
	    yield value
	    statement(s)

Example:

    def sampleGenerate():
        yield 100
        yield 500
        yield 800

Python examples of yield keyword

Example 1: Demonstrate the example with yield keywords by returning values multiple times on function calls.

# python code to demonstrate example of 
# yield keyword

def sampleGenerate():
    yield 100
    yield 500
    yield 800

# main code
for value in sampleGenerate():
    print(value)

Output

100
500
800

Example 2: Find the squares of the numbers till a given maximum value of the square from main function.

# python code to demonstrate example of 
# yield keyword

def generateSquare():
    count = 1
    while True:
        yield count*count
        count += 1  # next function execution
                    # resumes from here

# main code
for i in generateSquare():
    print(i)
    if i>=100:
        break

Output

1 
4 
9 
16
25
36
49
64
81
100





Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.
Learn PCB Designing: PCB DESIGNING TUTORIAL







Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.