Home > Backend Development > Python Tutorial > Share an example code about yield

Share an example code about yield

零下一度
Release: 2017-06-01 09:05:49
Original
1326 people have browsed it

The editor below will bring you a brief discussion on the preliminary understanding of yield. The editor thinks it’s pretty good, so I’ll share it with you now and give it as a reference. Let’s follow the editor and take a look.

is as follows:

def go():
  while True:
    data = 1
    r = yield data # data是返回值,r是接收值
    print("data", data)
    print("A1", r)
    data += 1

    r = yield data
    print("data",data)
    r += r
    print("A2", r)
    data += 1

    r = yield data
    print("data",data)
    print("A3", r)
    # 运行时此后若找不到下一个yield,则会报错StopIteration

my = go()
print("my", my)
print("None", my.send(None))
print(my.send("1"))
print(my.send("2"))
print(my.send("3"))
Copy after login

①my.send(None): means starting the coroutine. This step will return the data value after the first yield.

②send Once, the code run is the code between the two yields, and finally the data value after the next yield is returned. If the latter yield statement is missing, The error "Stoplteration"

③r = yield data

r is passed in by my.send('incoming data') Data

data is the data returned after running this section

[Related recommendations]

1. Detailed description of yield usage in Python

2. Analysis of the usage of and and or in python

3. Detailed explanation of yield and generator example codes in python

4. Introduction to how to use yield in Python

The above is the detailed content of Share an example code about yield. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template