FAQ: Generators - Generator Methods: send()

This community-built FAQ covers the “Generator Methods: send()” exercise from the lesson “Generators”.

Paths and Courses
This exercise can be found in the following Codecademy content:
Learn Intermediate Python3

FAQs on the exercise Generator Methods: send()

There are currently no frequently asked questions associated with this exercise – that’s where you come in! You can contribute to this section by offering your own questions, answers, or clarifications on this exercise. Ask or answer a question by clicking reply (reply) below.

If you’ve had an “aha” moment about the concepts, formatting, syntax, or anything else with this exercise, consider sharing those insights! Teaching others and answering their questions is one of the best ways to learn and stay sharp.

Join the Discussion. Help a fellow learner on their journey.

Ask or answer a question about this exercise by clicking reply (reply) below!
You can also find further discussion and get answers to your questions over in #get-help.

Agree with a comment or answer? Like (like) to up-vote the contribution!

Need broader help or resources? Head to #get-help and #community:tips-and-resources. If you are wanting feedback or inspiration for a project, check out #project.

Looking for motivation to keep learning? Join our wider discussions in #community

Learn more about how to use this guide.

Found a bug? Report it online, or post in #community:Codecademy-Bug-Reporting

Have a question about your account or billing? Reach out to our customer support team!

None of the above? Find out where to ask other questions here!

I don’t understand this code:

def get_students():
    student_id = 1
    # Write your code below:
    while True:
      if student_id % 2 == 0:
          val = yield student_id
          if val is not None:
            student_id = val 
            continue
          student_id += 1

student_generator = get_students()
student_generator.send(None)
student_generator.send(1000)
for student_id in student_generator:
  if student_id > 1050:
    break
  print(student_id)

Why is there val = yield student_id?
Does that act as a normal yield?

2 Likes

def get_students():
student_id = 1
while True:
if student_id % 2 == 0:
val = yield student_id
if val is not None:
student_id = val
continue
student_id += 1

student_generator = get_students()
student_generator.send(None)
student_generator.send(1000)

for student in student_generator:
if student > 1050:
break
print(student)

I got a problem understanding why the val variable becomes NoneType when we assign yield student_id to it.
At first this results in val equaling to 1000 but in the next iteration it becomes a None value for some reason. Could anyone explain this to me? Thanks in advance!

If you ignore .send for the moment then yield <expression> will always return None. You can try a very simple generator and if you assign the output of the yield in a standard next call you’ll get None.

You’ll find lots of generators never try to assign an output from it and it’s used as a statement instead-
https://docs.python.org/3/reference/simple_stmts.html#yield

It’s only when you use .send that you return a value from that expression. If you’re more familiar with .send then you could equate next(obj) with obj.send(None) if that helps you follow the flow.

1 Like

It is realy hard topic with difficult excamples

Yeah, this is the first topic I’ve run into on the platform that seems like it could really use some love. The quiz did not seem very well written and the lessons left me confused without any idea of how I might apply the concepts in code.

2 Likes

I’m Having a hard time understanding how this generator works, when is it yielding the value?

def generator(): count = 0 while True: n = yield count if n is not None: count = n count += 1 my_generator = generator() print(next(my_generator)) # Output: 0 print(next(my_generator)) # Output: 1 print(my_generator.send(3)) # Output: 4 print(next(my_generator)) # Output: 5

My current order is:
1st{ count = 0, n=None, 0 is yielded, count incremented }
2nd{ count = 1, n = None, 1 is yielded, count incremented }
3rd{ count = 2, n =3, count = 3, count incremented, 4 is yielded}
4th{ count = 4, n=None 4 is yielded, count incremented}

What is the actual order to get the output to match?

Do you have a link to the lesson? Unfortunately it’s not linked on this FAQ at the moment.

I’ve altered your code slightly to create a different example that might be useful to you-

def generator(): count = 0 while True: n = yield count print(f'At this point in the code n = {n}') if n is not None: count = n count += 1 my_generator = generator() print(my_generator.send(None)) print(my_generator.send(None)) print(my_generator.send(3)) print(my_generator.send(None))

It might be that first initialisation step that’s causing you trouble. If not please say so.

Here is the lesson: https://www.codecademy.com/courses/learn-intermediate-python-3/lessons/int-python-generators/exercises/generator-methods

Your example clears up when n is assigned its variable but im still lost on when the yield happens, i cant seem to wrap my head around it, does next() cause the whole loop to run up until the yield? or is the value from the previous iteration stored in count and yielded on the next iteration.

1 Like

There’s that first step in which you can only .send(None) which is equivalent to next and this input is effectively discarded.

After that whenever you yield the generator is effectively paused on this line →

n = yield count
  ^
# Arguably paused here, yield executes but assignment does not until next call

Note that it doesn’t actually execute this entire line, at that point only the right hand side has been executed and yield has passed a value but n inside the generator has not yet been assigned (on that iteration). This is why there are 4 numerical outputs but only 3 prints from inside the generator in the example I sent (the final .send never reaches the print inside the generator, it’s still halfway through the line above).

It’s only on the the next call to the generator that n is assigned.

There’s a handy tool at Python Tutor - Visualize Python, Java, JavaScript, C, C++, Ruby code execution which might help. It allows you to step through the code bit by bit so you can see where you are in terms of execution and what values you have.

1 Like

Okay it clicked. The visualization tool really helped and i see in your example how it all functions too. Thank you so much!

1 Like