Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Language feature: generators and yield keyword #9

Open
tusharsadhwani opened this issue Aug 16, 2023 · 0 comments
Open

Language feature: generators and yield keyword #9

tusharsadhwani opened this issue Aug 16, 2023 · 0 comments

Comments

@tusharsadhwani
Copy link
Owner

Generator functions are functions that contain the yield keyword.

Generator functions, instead of returning a value, return a generator object, which when called with the top level next() function, resumes the function and keeps running it until it yields a value, and then pauses its execution.

For example:

def generator():
    print("This runs first")
    yield 1
    print("This runs in between")
    yield 2
    print("This runs last")

gen = generator()
print(next(gen))
print(next(gen))
print(next(gen, 3))

Produces this output:

This runs first
1
This runs in between
2
This runs last
3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant