Help with error, please

Hello. I am trying to append a sentence as the last line of the string story and I am getting this error. Massive thanks in advance!:
NameError Traceback (most recent call last)
Cell In[117], line 1
----> 1 sentences.append(plotsentenceconclusion())

NameError: name ‘sentences’ is not defined

def paragraphbuilder():
    sentences = []
    narrative = 0
    if paracount > 1:
        sentences.append("   ")
    for _ in range(random.randint(1,50)):
        y = random.randint(1,20)
        if y in range(1, 4):
           sentences.append(sentencetype1())
        if y in range(5):
           sentences.append(weathersentence1())
        if y in range(6, 10):
           sentences.append(subjectsentence1())
        if y in range(11, 18):
           sentences.append(settingsentence1())
        if y in range(19, 20):
            narrative = narrative + 1
            if narrative == 1:
                sentences.append(plotsentence1())
            if narrative == 2:
                sentences.append(plotsentence2())
    sentences.append("\n")
    return " ".join(sentences)

""" Generate story """
paracount = 1
while paracount < numberparas:
    paragraphbuilder()
    paragraph = paragraphbuilder()
    print(paragraph)
    story = story + paragraph
    paracount += 1

Looks like that traceback is for a different cell than the one you posted. Can you double check what code is producing that error, and post it and the full traceback as formatted text?

Are you trying to modify the local variable sentences from a different cell?

Sorry, yes:

    sentences.append(plotsentenceconclusion())

In that case, you can’t access/modify sentences from the global scope. sentences is local variable to the function paragraphbuilder. It only exists during the call to paragraphbuilder, and ceases to exist the moment the function returns.

What you likely want to do is either a) put that line inside paragraphbuilder (when sentences exists), or b) change the line to instead modify the value that paragraphbuilder returned. For example

paragraph = paragraphbuilder()
# ...
paragraph += plotsentenceconclusion()

Sidenote: your current code contains an extraneous call to paragraphbuilder:

1 Like

Which cell do I put this in:
paragraph = paragraphbuilder()

paragraph += plotsentenceconclusion()