Madison
Madison

Reputation: 747

How to excuse an undeclared variable in Python?

Recently I've been creating a game but I'm having a problem. To calculate what you've hit on an enemy it uses the variable sword.

At this point the player may or may not have purchased a sword, therefore I get an error that says: "variable not declared". Is there a way to work around a variable that hasn't been declared yet?

Upvotes: 0

Views: 2363

Answers (5)

parselmouth
parselmouth

Reputation: 1668

I'm not sure of the full extent of your game. Is "sword" the only item that the player character can carry, or is their an implied inventory that is open ended? (e.g. the player character has a sack or backpack and can pick up items during game play.)

If you would like to give the character an inventory, you can use a simple list, or, if all items are unique - i.e. the character can have only ONE sword at a time, then a set would be appropriate.

class Player(object):
    def __init__(self):
        self.inventory = set( )

    @property
    def has_sword(self):
        return ('sword' in self.inventory)

me = Player( )
me.inventory.add('sword')
if me.has_sword:
    print "swish!"

Upvotes: 1

Larry Lustig
Larry Lustig

Reputation: 51000

You have two options.

The first is to ensure that a player always has a sword variable. Set it to None before the player obtains a sword and, when you need to know whether the player has a sword, check whether the variable is None:

 sword = None

 # do lots of stuff here

 if sword is None:
    print 'Hey, no sword!'
 else:
    print 'Chop, chop, chop!'

Another way to write this if sword is not allowed to be an empty string or an integer value of 0 is:

 if sword:
    print 'Chop, chop, chop.'

Your second option is to wrap every reference to the sword variable in a try block and swallow the NameError that might be raised:

 try:
    if sword == 10:
        print 'Choppity chop chop chop.'
 except NameError:
    pass

The first solution is (much) better.

Upvotes: 9

SpliFF
SpliFF

Reputation: 39014

There are several options. What wim has offered is fine but if your variable is actually a key in a dict then you can shorten it like so:

has_sword = my_items.get('sword', False)

The second value in the get() method is a default value for when the sword key doesn't exist.

PRO TIP: globals() and locals() provide direct access to variables declared in the global scope and in a function respectively. That means globals().get('sword', False) should be valid for a variable you've declared globally.

Finally, as wim suggests you aren't really going about this the right way. A more pythonic approach would be to use a class like this:

class Player():
  def __init__(self)
    self.sword = None

player = Player()
if player.sword:
  print "Off with his head!"

Upvotes: 1

voscausa
voscausa

Reputation: 11706

You can check if the variable exist in your globals or locals dict, or use :

try:
    a = b
except NameError:
    a = b = 1 

Upvotes: 0

wim
wim

Reputation: 363243

Without seeing more of your code, I would say the usual way to "excuse a variable that hasn't been declared yet" would be by handling the possibility of a NameError exception.

try: 
  # variable sword may or may not exist here..
  sword
except NameError:
  # handle this

Upvotes: 1

Related Questions