I want to add another guest to a generator, using send() method, that iterates over the guest_list.txt. I know I need to use the send() method, but I just can't understand the n = yield value logic.
The code below outputs the first 10 guests from the guest_list.txt. I want to add "Jane,35" to the guests that are being returned, as an 11th guest.
With;
guestlist_generator.send("Jane,35")
guests = {}
def read_guestlist(file_name):
text_file = open(file_name,'r')
while True:
line_data = text_file.readline().strip().split(",")
if len(line_data) < 2: # If no more lines, close file
text_file.close()
break
name = line_data[0]
age = int(line_data[1])
guests[name] = age
yield name
guestlist_generator = read_guestlist("guest_list.txt")
for i in range(10):
print(next(guestlist_generator))
guest_list.txt;
Tim,22
Tonya,45
Mary,12
Ann,32
Beth,20
Sam,5
Manny,76
Kenton,15
Kenny,27
Dixie,46
Mallory,32
Julian,4
Edward,71
Rose,65