How to use the last returned value by a function, as an input for the same function in a loop. Python
Question:
I have a problem using the last returned value from a function, as an input for the same function, I don´t know if it is possible to do.
For example, I have the following function:
def sample (x):
p=1+x
return p
sample(h)
and I want to use the last returned value "p" as the new data for h in a loop, the new function will look like:
def sample (x):
p=1+x
return p
sample(h)
for i in range (0,5):
h=sample(h)
The code works for iteration 1 and 2, but don´t update the values for iterations 3,4,5. Variable "p" in my real code, takes values from other functions or databases and changes (it´s a 3d array too), so it changes with each iteration. First input data "h" comes from a previous function too.
The input and output will be like:
h= [[[1.71, 1.8, 1.32, 1.56, 2.81], [1., 2., 1., 2., 1.]],
[[1.44, 1.47, 1.5, 1.02, 2.51], [1., 2., 1., 2., 1.]]]
p= [[[1.62, 1.15, 1.1, 1.05, 2.28], [1., 2., 1., 2., 1.]],
[[1.97, 1.85, 1.88, 1.03, 1.87], [1., 2., 1., 2., 2.]]]
Answers:
last_value = None
def sample (x):
p=1+x
last_value = p
return p
sample(last_value)
for i in range (0,5):
h=sample(last_value )
It is a bit difficult to grasp from your description, but I believe this might give you the desired result:
def sample(x):
p = 1+x
return p
h = 1 # Set the initial value here
for i in range(0, 5):
newH = sample(h)
h = newH
print(h) # Remove this print statement if you do not wish the result printed
I have a problem using the last returned value from a function, as an input for the same function, I don´t know if it is possible to do.
For example, I have the following function:
def sample (x):
p=1+x
return p
sample(h)
and I want to use the last returned value "p" as the new data for h in a loop, the new function will look like:
def sample (x):
p=1+x
return p
sample(h)
for i in range (0,5):
h=sample(h)
The code works for iteration 1 and 2, but don´t update the values for iterations 3,4,5. Variable "p" in my real code, takes values from other functions or databases and changes (it´s a 3d array too), so it changes with each iteration. First input data "h" comes from a previous function too.
The input and output will be like:
h= [[[1.71, 1.8, 1.32, 1.56, 2.81], [1., 2., 1., 2., 1.]],
[[1.44, 1.47, 1.5, 1.02, 2.51], [1., 2., 1., 2., 1.]]]
p= [[[1.62, 1.15, 1.1, 1.05, 2.28], [1., 2., 1., 2., 1.]],
[[1.97, 1.85, 1.88, 1.03, 1.87], [1., 2., 1., 2., 2.]]]
last_value = None
def sample (x):
p=1+x
last_value = p
return p
sample(last_value)
for i in range (0,5):
h=sample(last_value )
It is a bit difficult to grasp from your description, but I believe this might give you the desired result:
def sample(x):
p = 1+x
return p
h = 1 # Set the initial value here
for i in range(0, 5):
newH = sample(h)
h = newH
print(h) # Remove this print statement if you do not wish the result printed