0
def idf(total_word_freq, total_doc):#word_freq is a dict, total_doc is total number of documents
    idf = {}
    for word in total_word_freq:
        idf[word] = math.log(total_doc/total_word_freq[word]) + 1
    return idf

total_word_freq = word_freq(doc)
idf = idf(total_word_freq, len(textname))

UnboundLocalError: local variable 'idf' referenced before assignment

Why I got this?

  • 1
    Can you edit your question with full error traceback? – Rahul K P Oct 22 '22 at 21:23
  • 3
    You have only put a part of the code here, it is not possible to understand what the above parts of this code are, and this error says that you have probably used `idf` above the definition of this function, and this has caused you this error. If you paste more of your code here, I can guide you more. – Javad Oct 22 '22 at 21:30
  • 1
    @doxdeveloper Reusing `idf` for the accumulator for the return value is fine, since the function doesn't try to call itself recursively. Using it to capture the return value of the function is more problematic, assuming you want to call the function a second time. None of this, though, causes the reported error. (Nothing in the code shown *would* cause that error.) – chepner Oct 22 '22 at 21:50
  • Cannot reproduce with `idf = idf({'a':1,'b':2}, 2); print(idf)`. – wwii Oct 22 '22 at 23:40
  • Possible duplicate: [UnboundLocalError on local variable when reassigned after first use](/q/370357/4518341) – wjandrea Oct 23 '22 at 01:27
  • BTW, welcome back to Stack Overflow! Check out the [tour] and [ask], which has tips like making a [mre]. In this case it's required since we can't tell conclusively why the error is happening. – wjandrea Oct 23 '22 at 01:28

0 Answers0