Kinda dumb python question
Hi to all, this is my first post in the forum, but i've been reading for a while. I am working on learning Python right now and I need some help with this piece of code. I know it's really simple but I can't get the function to run the number of times I want, it just prints the text once. Any help will be appreciated :)
print "Text"
def do_n(fun, n):
if n<=0:
return
fun
do_n(fun, n-1)
do_n(stronz(), 5)```
[tab]print "Text"
def do_n(fun, n):
[tab]if n<=0: return
[tab]fun()
[tab]do_n(fun, n-1)
do_n(stronz, 5)```
And now the explanation!
```markup>>> def stronz():
... print "Text"
...
>>> stronz()
Text
>>> stronz
<function stronz at 0x7f94c2ae1938>
>>>
stronz() invokes the function. Now you may ask, "Why is the output of the stronz function not stored in the fun variable?" Well, print writes to stdout.
stronz is the object, as you can see above. The object is what we want to pass to the fun variable. You can then invoke the function with fun().
NOTE: next time you post code, use your text editor and replace all tabs with '[tab]', or some sort of equivalent. I look forward to the day the forums support white space.
alb00z wrote: Hey, thanks for stopping by. About adding the () when calling fun I had already done it but then I got this error "TypeError: 'NoneType' object is not callable" :/
Copy and paste my code in the previous post. MY CODE WORKS.
[SwartMumba@localhost Desktop]$ cat asdf.py
def stronz():
print "Text"
def do_n(fun, n):
if n<=0: return
fun()
do_n(fun, n-1)
do_n(stronz, 5)
[SwartMumba@localhost Desktop]$ python asdf.py
Text
Text
Text
Text
Text
[SwartMumba@localhost Desktop]$
Now, that error message you are talking about… Please read what I fucking post, else there is no point in me posting. To recap…
stronz() invokes the function. Now you may ask, "Why is the output of the stronz function not stored in the fun variable?" Well, print writes to stdout.
stronz is the object, as you can see above. The object is what we want to pass to the fun variable. You can then invoke the function with fun().
Are you ready to put the puzzle together?
>>> def stronz():
... print "Text"
...
>>> stronz()
Text
>>> a = stronz()
Text
>>> type(a)
<type 'NoneType'>
>>> a = stronz
>>> type(a)
<type 'function'>
>>>
Now look at your error message.
TypeError: 'NoneType' object is not callable