this maybe simple but how can I automatize this: for example, this is just for 2 steps but I want to do the same for 100 should I use looping or another kind of function
def earn(w,y):
return w y
def spend(w,x):
new_wealth = w -x
if new_wealth < 0:
print("Insufficient funds")
else:
return new_wealth
w0=0
w1=earn(w0,2300)
w2=spend(w1,1500)
w3=earn(w2,2300)
w4=spend(w3,1500)
print("w0,w1,w2,w3,w4 = ", w0,w1,w2,w3,w4)
CodePudding user response:
if you had a list of transactions with weather it was a spend or earn and the value you could try something like this
transactions = ['earn 2300', 'spend 1500', 'earn 2300', 'spend 1500']
string = ''
results = [0]
for n in range(len(transactions)):
string = 'w' str(n)
transactions_type = transactions[n].split(' ')[0]
transactions_value = int(transactions[n].split(' ')[1])
if transactions_type.lower() == 'earn':
results.append(earn(results[-1], transactions_value))
if transactions_type.lower() == 'spend':
results.append(spend(results[-1], transactions_value))
output = string ' = '
for value in results:
output = str(value)
which outputs
w0,w1,w2,w3,w4 = 0 2300 800 3100 1600
but this would depend on how you are storing this transaction information the method here works but is not ideal
CodePudding user response:
To repeat the same action, you should obviously use loops. Here is an example using a "for" loop with 100 iterations, appending each operation result in a list:
results = []
w = 0
for _i in range(100):
w = earn(w, 2300)
results.append(w)
w = spend(w, 1500)
results.append(w)
print(results) # [2300, 800, 3100, 1600, 3900, 2400 ... ]
You should obviously modify it for your purpose.