Python yield, pythonyield

Source: Internet
Author: User

Python yield, pythonyield

I saw the yield keyword in other people's code, read some documents, and explain my understanding.

 

A function that contains the yield keyword becomes an iterator. yield is at the same position as return, but does not exit after each result is returned, but waits for the next iteration, after the next iteration, execute the statement after yield until yield is encountered again, and a new result is returned.

Of course, those who are not familiar with yield may not understand the iterator (for example, I ^), so in a more general sense, if a function (SCRIPT) if repeated (loop) execution is required and the result of each loop is required, replace return with yield, for example:

>>> Def fib (max ):... n, a, B = 0, 0, 1... while n <max :... yield... a, B = B, a + B... n + = 1 >>>> f1.next () 0 >>> f1.next () 1 >>> f1.next () 1 >>>> f1.next () 2 >>> f1.next () 3 >>> f1.next () Traceback (most recent call last): File "<stdin>", line 1, in <module> StopIteration

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.