pmv - 10 months ago 28

Python Question

I have a function called

`add_ten`

I want to create a

`looper`

`list`

`add_ten`

`def add_ten(x):`

y = x+10

print 'value of x is ' + str(x)

print 'value of y is ' + str(y)

def looper(list,func):

for i in list:

return func(i)

I call the looper function

`looper([1,2],add_ten())`

I get this error.

`---------------------------------------------------------------------------`

TypeError Traceback (most recent call last)

<ipython-input-27-6510e446c709> in <module>()

----> 1 looper([1,2],add_ten())

TypeError: add_ten() takes exactly 1 argument (0 given)

How do I create the looper function properly so that it takes the right arguments?

Answer

Trying to understand the question, I arrive at the following working code:

```
#! /usr/bin/env python
from __future__ import print_function
def add_ten(x):
print('value of x is %s\nvalue of y is %s' % (str(x), str(x + 10)))
def looper(list, func):
for i in list:
func(i)
if __name__ == '__main__':
looper([1, 2], add_ten)
```

Output is on my machine:

```
value of x is 1
value of y is 11
value of x is 2
value of y is 12
```

Hope this helps in learning Python ;-)

Note in the implementation of `looper`

you for sure do not want to return early in the first iteration, as then only the first list element is processed with a result. Here above I just **call** it and the side effect of the print or whatever is defined in `add_ten`

"happens" ...