0

So, I have a function that is in a while loop. But when the while loop goes back, the varibles don't change and stay the same.

# x = players attack damage, y = Monster hp, b = Player hp, a = monsters attack

def damage1(x, y, b, a):

    print("----------\nyou did", x, "damage.\n----------")
    y = y - x
    print("monster has", y, "HP\n----------")

    time.sleep(0.5)
    
    print("The monster did", a, "damage\n----------")
    b = b - a
    print("You have", b, "HP")

The players and monsters hp are both a int and not randomized like the attacks are. When it loops back, both the hp values revert to their base value and not subtracting and saving that value. What did I do wrong.

jarmod
  • 71,565
  • 16
  • 115
  • 122
  • 1
    You aren't `return`ing the hp values – not_speshal Feb 22 '22 at 15:55
  • 2
    Where is the while loop? You need to return the modified values *and* assign them in the calling code. Also, related: https://stackoverflow.com/questions/575196/why-can-a-function-modify-some-arguments-as-perceived-by-the-caller-but-not-oth – jarmod Feb 22 '22 at 15:55
  • @jarmod do you think you could show me how I would do that, or is this a really simple thing I could find online. – CodeKid Games Feb 22 '22 at 16:01
  • It may be beneficial to research "function scope". Variable values inside the function will only last until the end of the function unless variables are brought out of the function by a return statement. – Brett La Pierre Feb 22 '22 at 16:03
  • Investigate using a Named Tuple or a dict and be sure to return what is done inside the function (or pass a mutable type data structure.) – dawg Feb 22 '22 at 16:10
  • The `damage1` function should return what it changed at the end of the function e.g. `return y,b`. And the calling code should assign these updated values e.g. `mhp, php = damage1(1, mhp, php, 2)` if the variables you are storing monster and player HP in are called `mhp` and `php`. Rename as appropriate. – jarmod Feb 22 '22 at 16:11
  • the issue is you are not returning any values with the function, also have use a funtion iteslf to overwrite a global var it just gets confusing, you are better calling the funtion to overwrite the var in the main script, b = func() for example – Tweaky Feb 22 '22 at 16:12

0 Answers0