yield keyword with example

natamacm

natamacm

Posted on June 9, 2020

yield keyword with example

The Python keyword yield is a keyword in the python, is similar to return, both are in used in a function and yield returns values.

In this article we'll go over several examples of the yield keyword.

Syntax of yield keyword
The syntax of the yield keyword is

        def function():
            statements
            yield value
            statements

Python Example of yield:

        def sampleGenerate():
            yield 100
            yield 200
            yield 300

The yield keyword can be used both in the shell and from a script.

yield examples

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

    # python example of yield keyword

    def sample():
        yield 100
        yield 200
        yield 300

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

The program above outputs this:

100
200
300

Example 2:
Find the squares of the numbers untill a maximum value. This can be done for various data types like integers or floats.

    # python yield keyword    
    def square():
        c = 1
        while True:
            yield c*c
            c += 1  

    for i in square():
        print(i)
        if i>=100:
            break

The program above outputs this:

1 
4 
9 
16
25
36
49
64
81
100
💖 💪 🙅 🚩
natamacm
natamacm

Posted on June 9, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related