So I'm working on a game, and here is my current code, which works fine:
print("Type directions() to see commands" )
def directions() :
print("Type North, East, South or West to move" )
move = input("North, East, South or West? ")
if move == "North":
north()
elif move == "East":
east()
elif move == "South":
south()
elif move == "West":
west()
def north():
print("You moved North")
x=0
x=(x+1)
print("You are at co-ordinates", x, "x:0 y" )
However, I am aware that later there will be a problem as x would be reset for each direction. When putting x=0
at the top of the code and removing it from the def north()
part, when running the code, Python gives me the error:
'UnboundLocalError: local variable 'x' referenced before assignment'
How can I code this so that 'x' is 0 to begin with, but can be altered by def
functions?
You can do one of 2 things: either use a global variable (which should be mostly avoided), or use return values. The global method:
or, the return value:
Judging by your question and the existence of
y
, you can do the following: