Patriots299
Patriots299

Reputation: 365

Use a variable in the for loop as input for a function

Suppose I have a function that sums:

def sum(x=10, y=15):
    return x + y

And then a for loop:

for i in range(5):
    a = sum() # 25
    b = sum(a) # 40
    c = sum(b) # 55
    d = sum(c) # 70

The above is not right, but hopefully gives the idea that first "a" is assigned 25. Then I would like the second iteration to call the sum function, but use the first iteration as input for the first parameter in the sum function. Then in a third iteration, there would be a call to the sum function, with the second interation's value. I just added letters to make the example more clear, but those letters would actually refer to the iterations of the for loop.

Does anyone know how can I implement something like this?

Upvotes: 0

Views: 1624

Answers (2)

Shanteshwar Inde
Shanteshwar Inde

Reputation: 1466

def sum(x, y=15):
    return x + y

a = 10
for i in range(5):
  a = sum(a)
  print("Output of "+str(i)+" iteration is : "+str(a))

print("Final output is : "+str(a))

As you explained in question:
You just need to assign one variable (i.e a=10) and pass it to function, then in first iteration function take first parameter as 10 and second parameter 15 which is default, it return 25. then in second iteration it pass 25 as first parameter and and default parameter as 15, it return 40 and so on ... this loop iterate for five time and at the end you will get result.

Upvotes: 2

Nordle
Nordle

Reputation: 3001

An alternative using a while loop:

def sum_(x, n, y=15):
    counter = 0
    while n > counter:
      x += y
      print(x)
      counter += 1

sum_(10, 5)

By passing another variable n, you can define the range of the loop which will run until the counter matches. I've added the _ to the function name as it is generally frowned upon to overwrite the built-in functions.

Upvotes: 0

Related Questions