Ask coding questions

← Back to all posts
I'm Trying to subtract a Variable from a Variable and its not working
KeeganMcGough (0)

I am making a random based fighter game.
I want to make it so when you do one punch its between 1-20 and then subtract that number from the opposing players health but it is not working.
If you could check it out it would be very helpful :D

print ("What Move?")
answer = raw_input(">")
if (answer == "punch"):
print ("Player 2 hits Player 1")
print ((Player1) - (punch))
print (Player1)
else:
print ("That is not a move")

https://repl.it/@KeeganMcGough/Fighter

Commentshotnewtop
HappyFakeboulde (225)

Line 18, error
You're trying to subtract punch -- a randomizer object -- from Player1, an integer.
You can't subtract an object from a number.
You'll need to convert the object to an integer somehow.

(Although, for this specific thing, it's very unnecessary to use a class just to generate random numbers -- you might as well just use a direct random.randint(13, 19))

PYer (3510)

@KeeganMcGough Make a function instead of a class:

def randomizer():
     return random.randint(13, 19)
KeeganMcGough (0)

@fullern000 I did that but now when It does player1 - punch it works but doesn't change player1 for the next print

IbraheemRodrigues (86)

@KeeganMcGough You perform the subtraction correctly, but the only thing that you do with that value is print it. You have not told python to store it as the new value of player1

player1 = player1 - punch will do this.
There is also player1 -= punch1, which is a short hand for the above
So your code should look like:

if (answer == "punch"):
    print ("Player 2 hits Player 1")
    Player1 = Player1 - punch # Perform the subtraction and store it back into the `Player1` var
    print (Player1) # Print this new value
else:
    print ("That is not a move")
PYer (3510)

@KeeganMcGough

15. Player1 -= punch
16. print(Player1) #not with the - punch