हिंदी

Describe what the following module is doing: c = start while True: value = yield c if value != None: c = value else: c += 1

Advertisements
Advertisements

प्रश्न

Describe what the following module is doing:

c = start
while True:
value = yield c
if value != None:
c = value
         else:
            c += 1
कोड लेखन
Advertisements

उत्तर

This defines a generator that produces a sequence of values beginning with start.

  • The first next() returns start.
  • If a value is sent using send(value), the generator replaces c with that value.
  • If None is sent, or ordinary next() is used, c is increased by one.
  • It continues indefinitely until the generator is closed.

Example:

def test(start=0):
    c = start
    while True:
        value = yield c
        if value is not None:
            c = value
        else:
            c += 1


g = test(5)
print(next(g))       # 5
print(next(g))       # 6
print(g.send(20))    # 20
print(next(g))       # 21
shaalaa.com
  क्या इस प्रश्न या उत्तर में कोई त्रुटि है?
अध्याय 8: Exception Handling & Generate Functions - EXERCISE [पृष्ठ १५७]

APPEARS IN

सीबीएसई Computer Science with Python [English] Class 12
अध्याय 8 Exception Handling & Generate Functions
EXERCISE | Q 5. | पृष्ठ १५७
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×