-1

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.

  • Where do you call these functions? – fynmnx Jul 30 '21 at 18:20
  • In the `addData(str)` function, if you want to modify the *global* variable, add `global stringData` as the first line in the function. The way it is now, Python is assuming the variable `stringData` is local to the function (not the global variable), and you are modifying it before initializing it in the function. (Or, you can pass it as a parameter to the function as `Ricardo` did.) – Chris Charley Jul 30 '21 at 18:39

2 Answers2

1

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()
Ricardo
  • 350
  • 1
  • 10
1

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
I'mahdi
  • 23,382
  • 5
  • 22
  • 30