0

I have trouble understanding Python Scope. If you can help, I'll be thankful. This is my code:

def msgCmd(x):
    if x[0] == '/':
        cmd = x[1:len(x)]
        print(cmd)

def Cmd(x):
    if x == "hello":
        print("Hi how can I help you?")
    elif x == "music":
        print("Let's rock!")

while 1:
    inp = input()
    cmd = ''
    msgCmd(inp)
    Cmd(cmd)

I am essentially trying to type in a command using /command and get two results. One being only the command name following slash and the other being a result of what it did. Say, I enter /music. I am expecting 'music' as the first result and 'Let's rock!' as the next. But, somehow I am failing to retrieve the second desired result, possibly due to a Python Scope problem.

Also, please explain why this code works as it should when I add global cmd at the top of the function msgCmd(x) like this:

def msgCmd(x):
    global cmd
    if x[0] == '/':
        cmd = x[1:len(x)]
        print(cmd)

And, why doesn't it run as desired when global cmd added here outside function:

global cmd

def msgCmd(x):
    if x[0] == '/':
        cmd = x[1:len(x)]
        print(cmd)

or here within the while loop:

while 1:
    inp = input()
    cmd = ''
    msgCmd(inp)
    global cmd
    Cmd(cmd)
  • 2
    note that the usage of `global` isn't recommended due to a few caveats: https://stackoverflow.com/questions/19158339/why-are-global-variables-evil – TNTzx Apr 21 '22 at 11:42

1 Answers1

1

return the value of msgCmd first:

def msgCmd(x):
    if x[0] == '/':
        cmd = x[1:len(x)]

    return cmd # right here

then get the value of that function so you can pass that value to another function:

    ...
    cmd_str = msgCmd(inp)
    Cmd(cmd_str)
TNTzx
  • 407
  • 2
  • 11