0

The title explains it all, why do I keep getting this? I can't seem to figure it out as the += operator has worked on strings before, so why wouldn't it now?

result = ""

def nounFunc():
    noun = str(input("Noun: "))
    result += noun


def adjectiveFunc():
    adjective = input("Adjective: ")
    result = ""


def verbFunc():
    verb = input("Verb: ")



def plural(name):
    thing = input(f"Plural {name}: ")

nounFunc()
  • Did you try to run the code? If so, were you able to conclude anything from the error you got from the runtime (in addition to what pycharm says)? See https://stackoverflow.com/a/423596/1424875 for further details. – nanofarad Apr 17 '21 at 04:15
  • I did run it, but couldn't get anything from it(I'm new to Python) – CataclysmicDev Apr 17 '21 at 04:17
  • 3
    I got the error `UnboundLocalError: local variable 'result' referenced before assignment`; `result` is a global so it needs to be properly declared `global` as per the link I gave. – nanofarad Apr 17 '21 at 04:18
  • It works if I take away the += operator and just make it =. – CataclysmicDev Apr 17 '21 at 04:18
  • 1
    Right, as @nanofarad said. If you CHANGE the value of a global within a function, you must tell Python that using the `global` statement. It would be better in EACH of these cases for you to return the values from these functions, instead of setting globals. – Tim Roberts Apr 17 '21 at 04:21
  • 1
    @CataclysmicDev It "works", but does it *actually* work or does PyCharm just stop complaining? When you use `=`, you assign to a local variable and end up not touching the global IIRC. – nanofarad Apr 17 '21 at 04:23
  • Though you added error to the title, adding to the question body as well would be better – srknzl Apr 17 '21 at 07:30

2 Answers2

2

Are you making a MadLibs thing? Here is better design, because globals are evil.


def nounFunc():
    return input("Noun: ")

def adjectiveFunc():
    return input("Adjective: ")

def verbFunc():
    return input("Verb: ")

def plural(name):
    return input(f"Plural {name}: ")

result = ""
result += nounFunc() 
result += " " + verbFunc()
print(result)
Tim Roberts
  • 48,973
  • 4
  • 21
  • 30
  • 1
    Yeah, I am making a MadLibs type game(I'm new to Python and wanted to challenge myself). Thank you for making my life easier with that code instead of the WAY longer code I was going to use:)! – CataclysmicDev Apr 17 '21 at 04:25
1

You need to do this:

def nounFunc():
    global result # <-- add this line
    noun = str(input("Noun: "))
    result += noun

This is because result is a global variable, which cannot be edited from a function without the global keyword. Note that you should avoid global unless you have to use it (return is preferred).

The reason it "works" if you make the += into a = is because in the latter case, you are making a new local variable called result.

knosmos
  • 636
  • 6
  • 17