Python Cmd: trying to return a value from a function but told it is being referenced before assignment

31 views Asked by At

im making a game with pythons cmd module but I've run into this problem. I have a function that I pass a variable into, the function changes it and returns it. but when I set the function equal to the variable it says that value has been referenced before assignment. however it doesn't do this if I don't set the function equal to value, but obviously value hasn't changed on the global level. I have tried to find a solution but can't thought I'd ask here. any help appreciated.

from cmd import Cmd

class stuff(Cmd):
    def do_command(self, args):
        value = command(value)

def command(value):
    value = "new value"
    return value

value = "value"

if __name__ == "__main__":
    prompts = stuff()
    prompts.cmdloop()
1

There are 1 answers

0
James.L On

ok i fixed it by just putting a golbal variable in the do_command function like so:

from cmd import Cmd

class stuff(Cmd):
    def do_command(self, args):
        global value
        value = command(value)

def command(value):
    value = "new value"
    return value

value = "value"

if __name__ == "__main__":
    prompts = stuff()
    prompts.cmdloop()