Python Builder Generator Usage example analysis

Source: Internet
Author: User
This example describes the Python builder generator usage. Share to everyone for your reference. Specific as follows:

With yield, you can let a function generate a result sequence, not just a value

For example:

def countdown (n):   print "Counting" while   n>0:     yield n #生成一个n值     

Next () calls the generator function to run until the next yield statement, where next () passes the return value to yield. And the function pauses abort execution. When next () is called again, the function will continue executing the statement after yield. This process continues until the function returns.

Instead of manually invoking next () as above, the for loop is usually used, for example:

>>> for I in Countdown (5): ...   Print I ...   

Next (), the return value of Send () is the argument after yield, the difference between send () and next () is that send () is the expression that sends a parameter to (yield N), as its return value to M, and next () is send a none to (yield N) expressions, it is necessary to distinguish between a call to next (), the return value of Send (), and a return value of (yield N), which are not the same. Look at the output can be distinguished.

def h (N): While   n>0:     m = (yield n)     print "M is" +str (m)     n-=1     

Hopefully this article will help you with Python programming.

  • Related Article

    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.