Код: Выделить всё
DICTIONARY = {
'a': 'apple',
'b': 'banana',
'c': 'cat',
'd': 'dog',
}
Код: Выделить всё
def alphabet():
while True:
try:
letter = yield #waiting for first input from send
while True:
try:
letter = yield DICTIONARY[letter]
except KeyError:
letter = yield 'default' # return 'default', if key is not found
except Exception:
letter = yield 'default'
except KeyError:
letter = yield 'default'
except Exception:
letter = yield 'default'
Код: Выделить всё
coro = alphabet()
next(coro)
print(coro.send('apple'))
print(coro.send('banana'))
print(coro.throw(KeyError))
print(coro.send('dog'))
print(coro.send('d'))
Код: Выделить всё
default
default
default
default
dog
Код: Выделить всё
default
default
default
None
dog
Подробнее здесь: https://stackoverflow.com/questions/790 ... th-1-yield
Мобильная версия