Invalid syntax in Python’s for statement Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Invalid syntax in Python’s for statement without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I am trying to run the code below, and when I run python tfidf.py (Python 2.6.9) I get SyntaxError: invalid syntax error in the line below, pointing to the for statement. What am I doing wrong?

def produceVector(blob, bloblist):
    ##### SYNTAXERROR: invalid syntax in the "for" in the line below #####
    scores = {word: tfidf(word, blob, bloblist) for word in blob.words}
    return scores

def tf(word, blob):
    return blob.words.count(word) / len(blob.words)

def n_containing(word, bloblist):
    return sum(1 for blob in bloblist if word in blob)

def idf(word, bloblist):
    return math.log(len(bloblist) / (1 + n_containing(word, bloblist)))

def tfidf(word, blob, bloblist):
    return tf(word, blob) * idf(word, bloblist)

Answer

That’s not a for statement, that’s a dict comprehension. Which was only introduced in 2.7. Generate an iterable of 2-tuples instead and pass it to the dict() constructor.

We are here to answer your question about Invalid syntax in Python’s for statement - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji