Reputation: 1404
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!!!
Upvotes: 0
Views: 645
Reputation: 781
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)
Upvotes: 1