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?
You have two options.
The first is to ensure that a player always has a
swordvariable. Set it toNonebefore the player obtains a sword and, when you need to know whether the player has a sword, check whether the variable isNone:Another way to write this if sword is not allowed to be an empty string or an integer value of 0 is:
Your second option is to wrap every reference to the sword variable in a try block and swallow the NameError that might be raised:
The first solution is (much) better.