0

I was using a for loop to pass the result of a method to the method again and complete the modification on two lists.

def loop(a, b)
    #modification on a, b
    return a, b
a = [1, 1, 1]
b = [2, 2, 2]
for i in np.arange(100):
    a, b = loop(a, b)

In my code where I encountered this question, I defined another method in the loop method:

def loop(a, b, c): # a = cash i own; b = shares i own; c=price
    buying = a[0]*0.1/c[-1] #number of shares I will spend
    a.append(a[-1])
    b.append(b[-1])
    if c[-1]/c[-2] > 1.01, order(a, b, c)
    def order(a, b, c):
        a[-1] = a[-2] - buying*c[-1]
        b[-1] = b[-2] + buying
        return
    return a, b

for i in np.arange(100):
    a, b = loop(a, b, c)

I want to store the cash and shares information in a, b lists. If the buying condition is not satisfied, the new element added to the list should just be the last one. If the buying condition is satisfied then the element just added to the list will be changed. However, when I run the code, at some point the new element added a, b will not be the last one in the list but the initial one, which ruins the whole thing.

Jerry Li
  • 25
  • 4
  • 3
    Yes, what's your question? – perigon Aug 02 '17 at 06:17
  • 1
    What is it you're trying to do? What is the actual problem you try to solve? What would the result be after the looping? What would the result be after a single call? And please [read about how to ask good questions](http://stackoverflow.com/help/how-to-ask), as well as learn about [the XY problem](http://xyproblem.info/) (of which your "question" is an example of). – Some programmer dude Aug 02 '17 at 06:17
  • 1
    What's the modification, the input and the expected output? – Alexander Aug 02 '17 at 06:18
  • 1
    What happened when you tested your code? And why are you using Numpy `arange` when the rest of your code is plain Python? – PM 2Ring Aug 02 '17 at 06:27
  • I edited the question to clarify it. I want to append a new element that is the same as the last element to the list through each iteration and change it when the "if condition" is satisfied. But when I run the code, the added element will change back to the first element instead of the last one. – Jerry Li Aug 02 '17 at 07:04

1 Answers1

0

It is the last Line of your order function. If you use just "return", Python use the last returned values, instead of the new ones. So if you remove that line, I think it works fine!

None return was explained here : None return in Python

Saeed Bibak
  • 46
  • 10