Ask coding questions

← Back to all posts
Generator object not callable (sorry about the messy code)
AidenParkerson (0)

I cant figure out how to use yield to return from a while-loop without breaking from the function. Is there anything i'm missing that is exclusive to repl? (I attempt to call it at lines 201 and 202)

Answered by PYer (4009) [earned 5 cycles]
View Answer
PYer (4009)

Hello @AidenParkerson! I'm not sure a generator object is what you're looking for, or you're confused on how to use the object. I'm going to try and explain some things, in case you are confused on some of these subjects.
A generator object can be iteratred by a loop.

for item in generatorobject:

Or you could try and convert it into a list:

l = list(generatoritem)

A generator can be made with a class or function, and you seem to be doing it with a function. When iterating, the function will run until it yields a value again. Then it will pass the value onto the loop it's running in. yield is different from return in that you will be able to run the function again without losing the previous value (if that makes sense, kind of hard to explain).
The error that has arisen is due to flawed logic rather than syntax. A generator object is generally used for tasks that require looping over something, like this:

def reversedlist(l):
  for i in reversed(l):
    yield i

Then you could iterate over reversedlist(mylist) if you wanted to iterate over it in reverse order. However, that might not be the best solution, it's just an example.
Anyways, you're going to need to do some logical thinking about what you want to do exactly. By reading over the previous comments, I think you are trying to create a countdown that runs simulataneously (if that's how you spell it), while the user is playing the game.
Try using something like the threading package. Yet you seem to be a relatively new coder (no offense, I'm talking analytically), and I'm not sure this is the best thing to be attempting. You've got coding knowledge, but I think you need to try and plan out exactly what you want to happen, in a logical systematic way. Try writing a flow chart, or pseudo-code. If you show us want you want logically, we can help supply the code that you would have to use to complete the task.

InvisibleOne (2990)

I think you need to rethink exactly what you want that loop to do, what is the purpose of it?

AidenParkerson (0)

@InvisibleOne What I am attempting to do is use a counting timer with a multiprocessing import to run a timer alongside a game. For it to work it is required that I find a way to return from this function in a while-loop without breaking. I need to assign it to a variable. I have seen code that an do this via 'yield', instead of 'return'. I am sure this code is correct but repl doesn't seem to be accepting it. Or it might be from another version of python. I am not sure.