Updating an integer variable after it has been modified by a def

Viewed 42

===EDIT SOLVED! COMPLETED CODE IN COMMENTS BELOW!===

Making a text based role play game. Developing HP system. I've managed to make the HP and damage definitions. I need to make it so it updates the HP variable after every instance of damage that is taken.

I have only been coding for a week and don't know the terminology I'm looking for so I've not been able to search for an answer successfully but I've been trying to find an answer for about two hours now.

import random

hit_points = 20
d4_damage = random.randint(1, 4)
d6_damage = random.randint(1, 6)
d8_damage = random.randint(1, 8)

def hp_loss_small():
   for x in range(1):
       return hit_points - d4_damage


print (hp_loss_small())

def hp_loss_medium():
   for x in range(1):
       return hit_points - d6_damage


print (hp_loss_medium())

def hp_loss_large():
   for x in range(1):
       return hit_points - d8_damage


print (hp_loss_large())

Correct result would be if you ran a damage def and lost 4 hit points, it displays 16. But it doesn't update the hp variable, so if you take another 2 damage you go to 18 hp. I need it so it'd update the variable and go to 14.

2 Answers
 for x in range(1):

You can omit this completely, since this only runs the statement once.

When you return a value from a function, you can assign the result to a variable. In your case, you'd do hit_points = hp_loss_small(). Additionally, you should pass the current hit points as a parameter (def hp_loss_small(hit_points)), and call it as hp_loss_small(hit_points).

In case anyone else finds this while searching for a similar problem here is my finished code:

import random

hit_points = 20
d4_damage = random.randint(1, 4)
d6_damage = random.randint(1, 6)
d8_damage = random.randint(1, 8)

def dead():
    if hit_points < 1:
        return ('dead message ')
    else:
        return (' ')

def hp_loss_small(hit_points):
    return hit_points - d4_damage

print (hp_loss_small(hit_points))
hit_points = hp_loss_small(hit_points)
print (dead())

def hp_loss_medium(hit_points):
    return hit_points - d6_damage

print (hp_loss_medium(hit_points))
hit_points = hp_loss_medium(hit_points)
print (dead())

def hp_loss_large(hit_points):
    return hit_points - d8_damage

print (hp_loss_large(hit_points))
hit_points = hp_loss_large(hit_points)
print (dead())

Related