“local variable ‘stringData’ referenced before assignment” error in python [duplicate]

Solution for “local variable ‘stringData’ referenced before assignment” error in python [duplicate]
is Given Below:

I’m getting this (annoying) error about a variable. Here is my code, I don’t get what’s causing it and don’t know how to fix it:

stringData=""
newLine = True

def displayData():
    print(stringData)

def addData(str):
    if newLine and stringData != '':
        stringData += f'n{str}'
    else:
        stringData += str

It does not give much context for the error and I can’t find out how to fix it.

Careful, your variable str is a reserved keyword and shouldn’t be used as a variable name. That said, that’s not the source of your issue.
The code below works by overwriting the value of stringData.

stringData=""

newLine = True

def displayData():
    print(stringData)

def addData(my_str,stringData):
    if newLine and stringData != '':
        stringData += f'n{my_str}'
    else:
        stringData += my_str
    return stringData

stringData = addData('4',stringData)
stringData = addData('3',stringData)
displayData()

you can use class:

class myData:
    def __init__(self):
        self.stringData=""
        self.newLine = True

    def displayData(self):
        print(self.stringData)

    def addData(self, str):
        if self.newLine and self.stringData != '':
            self.stringData += f'n{str}'
        else:
            self.stringData += str

then:

md = myData()
md.addData("Hello")
md.displayData()

OUT : 
Hello

then:

md.addData("World")
md.displayData()

OUT:
Hello
World