Return multiple values over time - python

Okay, so is there a way to return a value from a function - the way return does - but not stop the function - the way return does?
I need this so I can keep returning values every so often. (Delays provided by time.sleep() or whatever.)

I think you are looking for yield. Example:
import time
def myFunction(limit):
for i in range(0,limit):
time.sleep(2)
yield i*i
for x in myFunction(100):
print( x )

def f():
for i in range(10):
yield i
g = f().next
# this is if you actually want to get a function
# and then call it repeatedly to get different values
print g()
print g()
print
# this is how you might normally use a generator
for i in f():
print i
Output:
0
1
0
1
...
9

Related

Deep copy index integer using lambda

func = []
for value in range(5):
func.append(lambda: print_index(value))
def print_index(index_to_print):
print(index_to_print)
for a in func:
a()
When I run the code above, the output is
4
4
4
4
4
Why is it not ?
0
1
2
3
4
What can I do to make it like the above.
I have tried importing copy and using copy.deepcopy(index). I didn't work probably since index is an integer.
Is lambda part of the reason it is not working.
Thank you for your help!
Not quite sure what you are trying to achieve but the reason that it is printing all 4s is because Python uses dynamic name resolution of variables, that is the value of value when the functions are executed (not when it is declared) is used.
If you really need a function to print the value then you need to create a closure, which means creating the function inside another function, e.g.:
def make_closure(v):
return lambda: print_index(v)
func = []
for value in range(5):
func.append(make_closure(value))
Now this outputs:
In []:
for a in func:
a()
Out[]:
0
1
2
3
4
As #AChampion said, Python calculates the value of value when it needs to and not while executing the loop.
However for me it seemed easier to do the following fix.
func = []
for value in range(5):
func.append(lambda v = value: print_index(v))
def print_index(index_to_print):
print(index_to_print)
for a in func:
a()
This is setting the default argument in the function which gets calculated during the loop execution. The code above is the same as saying :
func = []
for value in range(5):
def anonymous_function(v=value):
print_index(v)
func.append(anonymous_function)
def print_index(index_to_print):
print(index_to_print)
for a in func:
a()

using functions: print vs return

What is correct way to use data from functions in Python scripts?
Using print, like:
var1 = 'This is var1'
def func1():
print(var1)
func1()
Or - with return:
var1 = 'This is var1'
def func1():
return var1
print(func1())
Both give same result:
$ ./func_var_print_return.py
This is var1
You should return a value when the purpose of the function is to produce a value. This is so functions can use other functions. For example
def add(x,y):
return x + y
def multiply(a,b):
product = 0
for i in range(b):
product = add(product, a) # Note I am calling the add function
return product
Testing
>>> multiply(5,4)
20
Note that I used the return value from add within my multiply function. If I only printed the value from add, I would have been unable to do that.
It depends on the situation. In general I would return it so you can print if you want but if you code changes at some point you can perform other operations with the value
You should always try to return the value.
Think of unit tests -> How would you verify the value if it's not returned?
And as mentioned by "meto" before, if your code changes you can still perform other operations with the value.

Nested while loop counter not returning inner loop function

I have a counter function, counter(), which is supposed to first count to 2 and return one function
h() and then continue counting to 3 and return the function g() and break.
def h():
return "hi"
def g():
return "hallo"
def counter():
i = 0
# If i is equal or less than 2, return the function h() and continue
while i <= 2:
i = i +1
return h(),i
continue
# If i equals 3, return function g() and break/end counting
# The current issue with this code is that the function g()
# isn't returned and the condition itself doesn't seem to
# respond, or count up to 3 from 2.
if i == 3:
return g()
return i
print counter()
return h(),i
the above line returns from the function, and the rest of the code is not run.
are you looking for print() ?
Your problem is the return statement.
When a return statement is encountered the function terminates, and then passes the return value to the caller (or None).
Which means your code will only work until the first return is encountered, and then your loop will exit.
Perhaps you are looking for yield or print?

How to simultaneously access a global variable used inside while loop in another function?

I want to access the value of a variable which is being modified by the while loop, to be continuously printed outside loop. What I did:
x=0
def funcA():
global x
while True:
x=x+1
return x
def funB():
print x
Now, I want x to keep print continously:
1
2
3 and so on!
But it does not. I DONT WANT THIS:
def funB():
while True:
print x
That is to say that I dont want any while loop inside function funcB().
Thank you very much!
I don't know if this is what you are looking for, but you could use a generator.
def funcA():
x = 0
while True:
yield x
x += 1
def funcB():
for x in funcA():
print x #=> 1, 2, 3...
You don't have a useful loop anywhere. In funcA, you have a while True:, but it just does a return every time through the loop, meaning it just runs once.
So, you could put a loop outside the two functions:
while True:
funcA()
funB()
Or, you could fix funcA so it loops forever instead of just once, then call funB from inside it:
def funcA():
global x
while True:
x=x+1
funB()
Or you could pass funB to funcA and have it call whatever it gets passed:
def funcA(*functions):
global x
while True:
x=x+1
for function in functions:
functions()
funcA(funB)
Or you could make funcA yield each time through the loop instead of returning, and use that to drive funB:
def funcA():
global x
while True:
x=x+1
yield x
for _ in funcA():
funB()
Or… there are all kinds of things you could do. The question is what you actually want to do. If you can explain that, someone can help you write it.
Meanwhile, you don't actually need a global variable in most of these cases. Given that funcA is already trying to return x, you can just pass the returned value in to funB in the outer-loop version, or pass x itself to funB and to function in the next two versions, and pass the yielded value in the generator version, …
A callback would work and avoids the need for a global x:
def funcA(cb):
x = 0
while True:
x=x+1
cb(x)
def funB(a):
print a
funcA(funB)

Python - how to define a variable using a function?

I have a function that returns a number. I want to assign a variable to have this value, but python gives a runtime error when I say temp = foo(i, j) : NameError: name 'foo' is not defined. Note that I've changed the function bodies of bar and foo around, obviously having a function that just returns 1 is useless, but it doesn't change my error.
sum = 0
for i in range(2, 100):
for j in range(2, i):
temp = foo(i, j)
if (temp > 100):
sum = sum + 1
print sum
def bar (n, a):
r = 1
return r
def foo (n, a):
s = bar(n, a)/factorial(5);
return s
def factorial (n):
r = 1
for i in range (2, n + 1):
r *= i;
return r
Names in Python do not exist until they are bound. Move the def foo(...): block above the code that uses foo().
Your definition of foo is AFTER you use it in the file. Put your function definition above the for loop.
As per other answers, your issue is the order in which you run your code: foo hasn't been defined yet when you first call it. Just wanted to add a comment about best practices here.
I always try to put everything in a function and then call any scripts at the bottom. You've probably encountered this pattern before, and it's a good habit to get into:
CONSTANT = 5
def run():
for i in xrange(CONSTANT):
print foo(i) # whatever code you want
def foo(n):
# some method here...
pass
if __name__ == "__main__":
run()
if you run this with python script.py or by hitting f5 in idle, run() will be executed after everything is defined.
By following this pattern you don't have to worry about the order you define your functions in, and you get the added benefit of being able to import foo with other functions without having your script execute during the import, which is probably not a desired behavior.

Categories

Resources