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)
1

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

1 Comment

It proved to be helpful. Thank you.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.