how to declare value as none the redeclare it then use it for an if statement in python?

74 Views Asked by At

My question is pretty simple how do how to declare value as none the redeclare it then use it for an if statement in python?

global command
command = None

def user_commands():
    def take_command():
    try:
        with sr.Microphone() as source:
            print('listening...')
            voice = listener.listen(source)
            command = listener.recognize_google(voice)
            command = command.lower()
            if 'alexa' in command:
                command = command.replace('alexa', '')
                print(command)
    except:
        pass
    return command

def run_alexa():
    global command
    command = user_commands()
    ...

    if 'Play' in command:
        ...

what is happening when I do this is: TypeError: argument of type 'NoneType' is not iterable

What I am doing is creating an alexa which ask to take commands then do the command. the variable for the command is set equal to the person says but in python it doesnt like to have a variable without a type so I said no then said ill redeclare it but it does not work,

2

There are 2 best solutions below

1
CaffeineDependent On

In your particular case, you are using the variable before you set it - which is not exclusive to global variables. That said; you may be confused on how the global keyword works.

global allows you to create, or modify, a variable from within an enclosed scope, that will be elevated to the global scope.

For example, you can try this in your REPL:

 >>> foo = "x"
 >>>
 >>> def bar():
 ...     foo = "y"
 ...
 >>> print(foo)
 'x'
 >>> bar()
 >>> print(foo)
 'x'

If you use the global keyword, however, it will be set when you modify it in the function.

 >>> foo = "x"
 >>>
 >>> def bar():
 ...     global foo
 ...     foo = "y"
 ...
 >>> print(foo)
 'x'
 >>> bar()
 >>> print(foo)
 'y'
2
rockerbacon On

The global keyword can be deceptive. It is not used for declaring a global variable, but rather for instructing the interpreter about what scope to use in future variable references. Let me try to explain it in another way:

When you write global command you’re trying to say “interpreter, please create a global variable named command”. But in reality global command actually means “interpreter, whenever you see a variable named command inside this function, you should look for it in the global scope”.

With all that said, you just need to define the variable in the global scope (outside any functions). Then, all functions that want to access this global variable should include the expression global command:

command = None

def user_commands():
    ...
    ...
    return command

def run_alexa():
    global command
    command = user_commands()