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 l
Solution 1:
Create a generator instead.
deftriangle():
res = 0
inc = 1whileTrue:
res += inc
inc += 1yield res
t = triangle()
printnext(t)
printnext(t)
printnext(t)
printnext(t)
EDIT:
Or perhaps a coroutine.
defsummer():
res = 0
inc = 0whileTrue:
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)
Solution 2:
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:
Solution 3:
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.
Post a Comment for "Returning Values From Inside A While Loop In Python"