Level 9 : What happens when we send() values into a generator?


def accumulator():
    total = 0
    while True:
        value = yield total
        if value is None:
            break
        total += value

gen = accumulator()
print(next(gen))
print(gen.send(10))
print(gen.send(20))
print(gen.send(None))

Author: SandhyaR | Tags: iterator | 1859+ Python FAQs | Share
inherit | operator-or | namedtuple | nested-loop | module | list-slicing | name-mangling | precedence-and-associativity | thread | time-series-with-pandas | virtual-environment | matrix-list-comprehension | variable | logical-operators | random-function | type-conversion | oop | zip-function | using-assertions-(assertequal,-assertraises) | random | zip | thread-synchronization | zfill-function | enumerate() | default-mutable-argument | keyword | operators | floats | directory-operations | filter | file-handling | indexing:-loc-vs-iloc | using-map()-for-transformations | writing:-write(),-writelines() | input-function | comment | working-with-file-paths | using-lists-as-stacks | encoding | dictionaries | exception-handling | class | tuples | match | yield | dictionary-comprehensions | expression | methods | immutable-data-type | input-function | string-method | generators | list-methods-and-slicing | pep | unit-testing | __all__-attribute | lambda-function | class-and-instance-variable | namespace | string-formatting | loop-control-statements | class-and-inheritance | for | filter-function | round-function | parsing-with-strptime | constructor | literal-characters-and-special-characters | reading:-read(),-readline(),-readlines() | key-value-pairs | complex | math | def | lists | dataframe-and-series-objects | benefit | exception-handling | staticmethod | touples | loops | why-use-multiprocessing-over-threading?-(gil) | dictionary | regular-expressions | iterator | while-loops | booleans | decimal | indentation | complex-number | list,-set,-and-dictionary-comprehensions | single-inheritance | polymorphism | joining-and-merging-dataframes | multiple-inheritance | package-management | binary-operation | using-the-threading-module | set | sum() | control-flow | type_conversion | using-join()-and-is_alive()-methods | data-type | context-manager | syntax-error | threading | typeerror | numeric | invalid-list | recursion | tuple | join | while-and-for-loop | __future__ | defining-functions | reading-and-writing-files | creating-custom-modules | postfix | debugging | introduction-to-python | datetime.date,-datetime.time,-datetime.datetime | data_structure | static-method | data-structure | else-statement | string-concatenation | swapping | identity-operator | expand-tab | exponentiation | generators-in-python | version | higher-order-function | arbitrary-arguments-(*args,-**kwargs) | python-history | frozenset | control-flow | working-with-temporary-files-using-tempfile | descriptors | file_handling | sum-function | heap-memory | slicing | init | membership-operators-(in,-not-in) | regular-expression | goto-function | map-function | logical-operator | data-type | string-manipulation | function | append | test-discovery | conditional-statement | asyncio-module | numpy | method | classes | operations | __init_subclass__ | comparison | while-else-loop | filtering-and-indexing | stack | formal-and-actual-parameter | tuple-unpacking | datatype | raise-statement | statement | factorial-function | list-method | immutability | managing-directories-with-os-and-shutil | string-slicing | memory | sys-module | access-modifier | operand | copy | class-and-object | type-conversion | attribute | string-slicing | iterators | multiple-except-blocks | asyncio | file | list-comprehension | tuple-methods | slice | formatting-with-strftime | creating-and-starting-threads | boolean-and-non-boolean | built-in-function | virtual-environment | sorted | control-statement | list | feature | dictionary-methods | installation | center | python-repl | syntax-error | sys | class-decorators | destructor | loop | sets | advanced-file-operations | inheritance | identity-operators-(is,-is-not) | list-vs-tuple | difference-between-threads-and-processes | list-mutation | head-and-tail | list-comprehension | using-yield-in-functions | import-method | list-join | global-variable | using-os-and-pathlib-modules | logical-operation | call | int | turtle | interpreter | conversion | assignment-operator | deep-copy | identifier | magic-method | multithreading | handling-missing-values-(fillna,-dropna) | data-type-conversions | implementation | lambdas | application | introduction-to-multiprocessing | string-formatting | object-attribute | min-max-function | syntaxerror | mapping-function | opening-files-(open()) | boolean | quantifiers-(*,-+,-?,-{}) | error-handling | mathematical-function | list-operation | conditional-statement | indexing | mathematics | python_version | python-module | objects | python-django | list-indexing | compute | file-handling | binary | counter | docstring | escape-operator | encapsulation | set-operation | exception | split | array | memory-management | round | matrix | global-variable | oops | boolean-masking | shallow-copy | decorator | list-comprehensions | arithmetic-expression | sorting | iterable | data-types | range | introduction-to-threads | counter-function | library | sorting-and-ranking | thread-safe-data-structures-(queue.queue) | functions | with-statement | software-design | built-in-modules | data-structure | design-principle | lambda-functions | odd-number | collection | syntax | data-structures-in-python | conditional-statements | operator-overloading | datetime | assert | method-overloading | async | multiprocessing | scientific-notation | id-function | mysql | lambda | overflow | identity-operator | walking-through-directories-using-os.walk() | recurssion | logical-operator | aggregating-data-with-functools.reduce() | comprehension | regex | type-conversion-and-casting | default-arguments | command-line-parsing | max-min | intering | matplotlib | python | anchors-(^,-$) | collections | condition | pseudocode | strings | arithmetic-operation | integers | loop-control | input | generator | data-structures | string-iteration | integer | dicts | reading-and-writing-large-files-efficiently | function-and-scope | assignment-operators | while-loop | update | string | min-function | rollback | built-in | bitwise-operator | error | floating-point-precision | math-copysign | python-operators | multiple-inheritance | pickling--unpickling | gil | functional-programming | python-syntax-and-structure | pass | raise | format | operator | working-with-binary-files-(rb,-wb) | parameter | pandas | working-with-dates-and-times | return-statement | using-else-and-finally | basic | error-handling | else | precedence | function-argument | fabs-function | string-methods | overriding-methods | string-method | global-keyword | operator-and | bitwise-operator | bitwise | choice | functional-programming | built-in-function | version-check | global | print | print-statement | mutable ...