Slater Victoroff
Slater Victoroff

Reputation: 21934

Returning values from inside a while loop in python

I don't know if this is a simple question or impossible or anything, but I couldn't find anything on it so I figured I would ask it.

Is it possible to return values from a while loop while that loop is still running? Basically what I want to do is have a vector constantly updating within a while loop, but able to return values when asked without stopping the while loop. Is this possible? Do I just have to break up the program and put the while loop in a separate thread, or can I do it within one function?

Also I would prefer a method that is not computationally intensive (obviously), and one compatible with a rate-limited while loop as this one will certainly be rate-limited.

Again, if this is a stupid question just tell me and I will delete it, but I wasn't able to find documentation on this.

Code I am trying to implement this with:

def update(self, x_motion, y_motion, z_motion):
        self.x_pos += self.x_veloc
        self.y_pos += self.y_veloc
        self.z_pos += self.z_veloc
        self.x_veloc += self.x_accel
        self.y_veloc += self.y_accel
        self.z_veloc += self.z_accel
        self.x_accel = x_motion[2]
        self.y_accel = y_motion[2]
        self.z_accel = z_motion[2]
while True:
self.update(x_motion, y_motion, z_motion)

print vector.x_accel

Something along those lines at least. It is important that these return outside of the while loop, so that the while loop runs in the background, but it only gives results when asked, or something like that.

Upvotes: 3

Views: 11515

Answers (3)

beoliver
beoliver

Reputation: 5759

What you are looking for is yield:

def func():
    while True:
        yield "hello"


for x in func():
    print(x)

Generators can also be written like list comprehensions:

Have a look at this question:

What does the "yield" keyword do?

Upvotes: 4

Mahmoud Aladdin
Mahmoud Aladdin

Reputation: 546

If I understand you and the code you want to do.

I may think of trying to find equations of position, velocity and acceleration with respect to time.

So you won't need to keep, the while loop running, what you need is to convert it to a function, and using the time difference between the 2 function calls, you can perform the calculations you want, only when you call the function, rather than having the while loop running all the time.

Upvotes: 0

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799310

Create a generator instead.

def triangle():
  res = 0
  inc = 1
  while True:
    res += inc
    inc += 1
    yield res

t = triangle()
print next(t)
print next(t)
print next(t)
print next(t)

EDIT:

Or perhaps a coroutine.

def summer():
  res = 0
  inc = 0
  while True:
    res += inc
    inc = (yield res)

s = summer()
print s.send(None)
print s.send(3)
print s.send(5)
print s.send(2)
print s.send(4)

Upvotes: 6

Related Questions