Envision, Create, Share

Welcome to HBGames, a leading amateur game development forum and Discord server. All are welcome, and amongst our ranks you will find experts in their field from all aspects of video game design and development.

Python and Local/Global etc. Variables.

I need help... :(

I do a bit of python scripting. I'm getting relatively good at it... although I don't do any strict teachings... I just pick up knowledge around the place...
I have a big problem though.

Here is a basic script outlining what I have.

Code:
animal = "ferret"

#--------------------

def bird(n):
     animal = "bird" 
     print "You found a", animal, "!"
     catch(1)

def catch(n):
     print "You caught the", animal, "!"

#--------------------

bird(1)

As all python users should see, the first print will say "You found a bird!"
And the second one (logically) should say "You caught the bird!"

However, Python is less logical than us, so it says
"You found a bird!"
"You caught the ferret!"

As the new string for 'animal' is defined locally in the fuction 'bird'.
How do I fix this so the variable carries over different functions?

Any help is appreciated.
 
I don't know much about Python (actually, I never used it), but maybe it is because you defined the local variable "animal" outside of a method? Make it an instance variable instead.
 
Most languages have a symbol in front of it so it can be set as local, global, etc.
Sorry if I don't know what that could be. :\

EDIT: try declaring the animal in the function to
"global animal"
EDIT: nevermind. guess you can't do that. weird. :\
EDit: Try this:

Code:
animal = "ferret"

#--------------------

def bird(n):
     global animal
     animal = "bird" 
     print "You found a", animal, "!"
     catch(1)

def catch(n):
     print "You caught the", animal, "!"

#--------------------

bird(1)

Since you declared it outside of the function it was set to global but once you change it inside that function, it became local to within the function itself.
 

Thank you for viewing

HBGames is a leading amateur video game development forum and Discord server open to all ability levels. Feel free to have a nosey around!

Discord

Join our growing and active Discord server to discuss all aspects of game making in a relaxed environment. Join Us

Content

  • Our Games
  • Games in Development
  • Emoji by Twemoji.
    Top