Local variable error

Hello. I am getting this error. Massive thanks in advance for helping me with this!!
“”" Generate story “”"
paracount = 1
while paracount < numberparas:
paragraphbuilder()
paragraph = paragraphbuilder()
print(paragraph)
story = story + paragraph
paracount += 1

UnboundLocalError Traceback (most recent call last)
Cell In[129], line 5
3 while paracount < numberparas:
4 paragraphbuilder()
----> 5 paragraph = paragraphbuilder()
6 print(paragraph)
7 story = story + paragraph

Cell In[128], line 16, in paragraphbuilder()
14 sentences.append(settingsentence1())
15 if y in range(19, 20):
—> 16 narrative = narrative + 1
17 if narrative == 1:
18 sentences.append(plotsentence1())

UnboundLocalError: cannot access local variable ‘narrative’ where it is not associated with a value

narrative = 0

def paragraphbuilder():
    sentences = []
    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)
narrative = narrative + 1

The variable narrative on the right hand side of this statement does not yet exist. So you’re getting an error because of that.

You could perhaps initialize it up at the top of the function, after sentences?

1 Like

Now I am getting a different error, but not the narrative one

Well that’s being caused by something else but I have no idea what. :joy:

Read the error message! What line does it point you to? What does it say about that line? These are critical habits for learning how to code. If your progress loop includes “ask someone on the internet” whenever there’s an error, you will code very, very slowly.

2 Likes

I put in a good try to fixing things before I ask for help. Now I getting this error in the same code:
TypeError: can only concatenate str (not “int”) to str

It sounds like you’re trying to add an int to a string. What line does it say that’s happening on?


TypeError Traceback (most recent call last)
Cell In[299], line 5
3 while paracount < numberparas:
4 paragraphbuilder()
----> 5 paragraph = paragraphbuilder()
6 print(paragraph)
7 story = story + paragraph

Cell In[298], line 19, in paragraphbuilder()
17 narrative = narrative + 1
18 if narrative == 1:
—> 19 sentences.append(plotsentence1())
20 if narrative == 2:
21 sentences.append(plotsentence2())

Cell In[295], line 7, in plotsentence1()
5 text = text + Plotverb2
6 text = text + " the "
----> 7 text = text + place
8 text = text + “.”
9 return text

So, following the traceback to the final line, it looks text + place is the problem. What’s the value of place?

1 Like

They are both strings. Text is a story that is being bult.

I am very confident that place is not a string. Where is it defined?

You’re right. I found it

1 Like

Now I am getting:
TypeError: unsupported operand type(s) for -: ‘str’ and ‘int’

I fixed it! James’s message helped interperet the error message.

George,

I ran through the responses and do not see a logical error addressed.

What do you think range(6,10) includes?

If your goal is to include number between 1 and 50, then try this and see what you are actually getting:

>>> list(range(1,4))
[1, 2, 3]
>>> list(range(5))
[0, 1, 2, 3, 4]
>>> list(range(6,10))
[6, 7, 8, 9]
>>> list(range(11,18))
[11, 12, 13, 14, 15, 16, 17]
>>> list(range(19,20))
[19]

Do you see any gaps?

Do you handle zero or anything higher than 20?

Now what does your for loop do?

for _ in range(random.randint(1,50)):

That does not say range(1,50) but it does say random.randint(1,50) and the code you shared is not showing where you imported random.

So what you are asking for is a random number ranging from perhaps 0 or 1 rarely, often in the twenties, and approaching 50. When you get that number, call it N, you are making the loop repeat from 0:N and thus 0 needs to be considered as do numbers above 20.

Perhaps a more pythonic way to do what you are doing is a sequence of if/elif/elif/…/elif/else clauses.

And, just FYI, ranges need to be used carefully as they return an iterator and in some contexts that is fine but other context require you to run the iterator to make something like a list in my example above.

1 Like