I am trying to use the def function in python to make a quick function to get the damage that is dealt by the player for my adventure game, but it’s not working.
def get_fighter_strength(dice, strength):
return (strength + dice)
# ... More code here ...
if char == ("fighter"):
realdamage = get_fighter_strength(d20, fighter_strength)
print("You rolled a", d20)
print("plus your bonus", fighter_strength)
print("Final damage is:", realdamage)
Variable in functions (unless declared globally) are only avalible to their function, and (essentially) cease to exist after the function. If you return the value, then you can save it elsewhere.
Basically there are things called scopes. There are variables in the global scope, like ones you define outside of functions. But when you make a function you’re now in a lower scope. And variables defined in the lower scope can’t be used in the global/higher scopes.
So when you define a variable in a function, nothing outside of the function has access to that variable. You could use the global keyword, but it is considered bad practice.
So as @Firepup650 suggested, just return the value instead.
If our posts helped, please mark the one that helped you the most as the solution so the thread can close.