Coroutine With Send in Python

Level 5276 keystrokes

This demonstrates a coroutine that receives values via send() and yields running averages.

Python code

# Generator-based coroutine that keeps a running average
1def running_average():
# total keeps sum of all values
2 total = 0
# count tracks number of values received
3 count = 0
# average stores the current running average
4 average = None
# Infinite loop to keep receiving values
5 while True:
# yield pauses and returns average, receives new value
6 value = yield average
# Only process if value was sent (not None)
7 if value is not None:
# Add value to running total
8 total += value
# Increment count
9 count += 1
# Calculate new average
10 average = total / count
11
# Create the coroutine object
12coro = running_average()
# Prime the coroutine by advancing to first yield
13next(coro)
# Send 10, get average 10.0
14print(coro.send(10))
# Send 20, get average 15.0
15print(coro.send(20))
# Send 30, get average 20.0
16print(coro.send(30))
# Clean up by closing the coroutine
17coro.close()

Output

10.0
15.0
20.0
Practice typing this code

Practice typing this code. Results are not recorded in the rankings.

Symbols in this code

The symbols you type in this Python code and how often they appear.

  • (× 10
  • )× 10
  • =× 8
  • .× 4
  • :× 3
  • _× 2
  • +× 2
  • /× 1

More Python examples at level 5

← Python typing practice