I'm struggling with making a function that changes the value of the coordinates if the parameters appropriate.
That's what I made:
class Move:
def __init__(self, x, y):
self.x = x
self.y = y
move = Move(5, 5)
def obstacle(axis, value, plus):
if plus is True:
if axis == value:
axis = axis 1
print(f"x = {move.x}, y = {move.y}")
elif plus is False:
if axis == value:
axis = axis - 1
print(f"x = {move.x}, y = {move.y}")
obstacle(move.x, 5, False)
The program should print: x = 4, y = 5
CodePudding user response:
What the program is currently doing is running obstacle(), going inside the "if plus is false" block and changing the axis value from 5 to 4, and that's it. To print: x=4, y=5 you can:
- Instead of the axis value change the move.x value
- Or print the axis value instead of move.x
CodePudding user response:
Here is the code rewritten to work as you expect. But note that as @IBeFrogs implies move is global so you may as well just change it directly.
class Move:
def __init__(self, x, y):
self.x = x
self.y = y
move = Move(5, 5)
def obstacle(inst, value, plus):
if plus is True:
if inst.x == value:
inst.x = inst.x 1
elif plus is False:
if inst.x == value:
inst.x = inst.x - 1
print(f"x = {move.x}, y = {move.y}")
obstacle(move, 5, False)
CodePudding user response:
Parameters in function only takes the value in variable not the variable. So when you write like this:
axis = axis 1
and
axis = axis - 1
You just change the parameter value axis. Replace the two lines with:
move.x = move.x 1
and
move.x = move.x - 1
And the final code is like this:
class Move:
def __init__(self, x, y):
self.x = x
self.y = y
move = Move(5, 5)
def obstacle(axis, value, plus):
if plus is True:
if axis == value:
move.x = move.x 1
print(f"x = {move.x}, y = {move.y}")
elif plus is False:
if axis == value:
move.x = move.x - 1
print(f"x = {move.x}, y = {move.y}")
obstacle(move.x, 5, False)