lomf
lomf

Reputation: 11

Generators function

MAX_STUDENTS = 50

def get_student_ids():
  student_id = 1
  while student_id <= MAX_STUDENTS:
    # Write your code below
    n = yield student_id
    if n != None:
      student_id = n
      continue


    student_id += 1

student_id_generator = get_student_ids()
for i in student_id_generator:
  # Write your code below
  if i == 1:
    i = student_id_generator.send(25)
  print(i)

Im quite confused, when i run the code below, i understand the the send function gives 25 as the yield value and assigns it to n, however when entering the if statement, checking if n is not None, wouldnt this create an infinite loop, since n is not none, would take us to the continue statement, which takes us back to the next iteration of the while loop, completely skipping the incrementing of student id

Upvotes: 1

Views: 57

Answers (1)

Chavez
Chavez

Reputation: 144

The first thing one can notice is that n will always be of type none except when you send 25 into the generator.

Let's look at the flow of the program

this is the driver code at the start of the program

student_id_generator = get_student_ids() #creates a generator class
for i in student_id_generator: #interates through the generator class
    if i == 1: # note that the first i == 1, so the first time the code hits 
               #this condition, it will be true 
        i = student_id_generator.send(25) #sets n to be 25
    print(i) #for the first iteration, will return 1, as the first yield is 1

now, since n=25 (you just sent 25 into the generator code), let's look at the generator

n = yield student_id # n=25
if n != None: #since n==25, n is not none
    student_id = n #student_id = 25
    continue #go back to the while loop
student_id += 1 # will not be run

Now that student_id = 25, for the next iteration in the driver code, it will yield 25, so 25 will be printed. But n will be None as nothing is sent to the generator, so student_id += 1 will be run. From there, the while loop kicks in and it will continue until 'student_id == 50', where the loop breaks.

Will there be an infinite loop? No. Because the condition 'n != None' only occurs once.

I hope this helps. If you are still confused, my suggestion is to take out a pen and paper and work out what happens to the code step by step. I did that to help myself understand it.

Upvotes: 2

Related Questions