59

It tells me line 1 and line 5 (new to debugging/programming, not sure if that helps)

def hi():
    print('hi')


def loop(f, n):  # f repeats n times
    if n <= 0:
        return
    else:
        f()
        loop(f, n-1)
>>> loop(hi(), 5)
hi
f()
TypeError: 'NoneType' object is not callable

Why does it give me this error?

0

4 Answers 4

75

You want to pass the function object hi to your loop() function, not the result of a call to hi() (which is None since hi() doesn't return anything).

So try this:

>>> loop(hi, 5)
hi
hi
hi
hi
hi

Perhaps this will help you understand better:

>>> print hi()
hi
None
>>> print hi
<function hi at 0x0000000002422648>
2
  • 4
    You're welcome. Also, you might want to call your function recurse or something similar since it doesn't actually loop... Mar 19, 2012 at 11:09
  • For anyone in the future seeing this after decorating a class/function: make sure you return something from the implementation of the decorator! Jun 12 at 3:26
6

Why does it give me that error?

Because your first parameter you pass to the loop function is None but your function is expecting an callable object, which None object isn't.

Therefore you have to pass the callable-object which is in your case the hi function object.

def hi():     
  print 'hi'

def loop(f, n):         #f repeats n times
  if n<=0:
    return
  else:
    f()             
    loop(f, n-1)    

loop(hi, 5)
3
  • 1
    What if the hi function took an argument, e.g. text, and printed the string passed as the variable text. How would that be handled?
    – Olivier
    Jun 20, 2018 at 9:56
  • try lambda arg: hi(arg)
    – Ajax
    Dec 17, 2018 at 19:55
  • With hi taking an argument, loop(hi, 5) still runs, outputting the expected string, eg 'hi'+<your passed text>. @OlivierdeBroqueville Feb 12, 2022 at 23:06
3

You should not pass the call function hi() to the loop() function, This will give the result.

def hi():     
  print('hi')

def loop(f, n):         #f repeats n times
  if n<=0:
    return
  else:
    f()             
    loop(f, n-1)    

loop(hi, 5)            # Do not use hi() function inside loop() function
1

I faced the error "TypeError: 'NoneType' object is not callable " but for a different issue. With the above clues, i was able to debug and got it right! The issue that i faced was : I had the custome Library written and my file wasnt recognizing it although i had mentioned it

example: 
Library           ../../../libraries/customlibraries/ExtendedWaitKeywords.py
the keywords from my custom library were recognized and that error  was resolved only after specifying the complete path, as it was not getting the callable function.

Not the answer you're looking for? Browse other questions tagged or ask your own question.