0

I wrote this script for illustration purposes only, because I'm getting the same "Context Action" suggestion from PyCharm elsewhere in a larger script (script running fine).

dog = "Hungry"
def animal(status):
    while True:
        if status == "Hungry":
            action = "Feed Me"
        print(action)  # Right here it's highlighting "action" and asking me to add global statement
animal(dog)

Am I not assigning the variable "action" locally within my function "animal()"; and therefore I can freely use it anywhere else within the same function? Can someone explain why it's suggesting to make it a global variable?

Thank you!!!

Omar AlSuwaidi
  • 1,187
  • 2
  • 6
  • 26
  • 4
    What would happen if `status` was not `"Hungry"` in your current code? – DavidG Nov 03 '20 at 16:32
  • PyCharm should *also* say "Local variable 'action' might be referenced before assignment ". – MisterMiyagi Nov 03 '20 at 16:55
  • Does this answer your question? [Short description of the scoping rules?](https://stackoverflow.com/questions/291978/short-description-of-the-scoping-rules) – MisterMiyagi Nov 03 '20 at 16:57
  • @DavidG I see what you're trying to say, the print would result in an error. However, my actual code was set in a way such that the "while" and "if" statements had the same conditions, so it would've never printed unless both conditions were met. But you made it clear for me now, thanks!!! – Omar AlSuwaidi Nov 03 '20 at 19:09

1 Answers1

1

You are only setting action in the function scope if status == "Hungry", but if status != "Hungry", action is not set in the local scope. Now I can't really tell because you only posted part of you code, but I bet you have a variable named action in the outside scope - PyCharm thinks you want to access that, and therefore wants a global statement. If you do not want to mix the local and outer action, just set it to something else in a else clause:

dog = "Hungry"
def animal(status):
    while True:
        if status == "Hungry":
            action = "Feed Me"
        else:
            action = ""  # just set action to something to make sure it exists either way
        print(action)
animal(dog)
Xtrem532
  • 756
  • 8
  • 19