Search code examples
pythondice

Dice rolls and defining dmg_to_enemy


I am having an issue with defining dmg_to_enemy in this function. I figured if I used random.randint to define dmg_to_enemy within the function, and then used return I would be able to print it outside of the function. Currently, when I run this code it returns dmg_to_enemy is not defined. I need to be able to define it so that I can use it for other functions. I am relatively new to coding and would like to know what I am doing wrong.

dwarf_class = "Thane"
def dice_rolls_combat(dwarf_class):  
    if dwarf_class == "Thane":
        dmg_to_enemy = random.randint(1, 8)
        return dmg_to_enemy
    elif dwarf_class == "Mekanik":
        dmg_to_enemy = random.randint(1, 5)
        return dmg_to_enemy
    elif dwarf_class == "Ancestrite":
        dmg_to_enemy = random.randint(1, 3)
        return dmg_to_enemy
    elif dwarf_class == "Prisoner":
        dmg_to_enemy = random.randint(1, 5)
        return dmg_to_enemy
    elif dwarf_class == "Civilian":
         dmg_to_enemy = random.randint(1, 4)
         return dmg_to_enemy
dice_rolls_combat(dwarf_class) #outside of function
print(dmg_to_enemy) # outside of the function

Solution

  • The variable dmg_to_enemy is local in its parent function and does not exist outside of it. You seem partially aware of this as you have a single line return dmg_to_enemy, although its indentation level means it will only return a useful result when that condition fires (dwarf_class == "Civilian"). Decrease the indentation level to make that part work.

    The other half is using that returned value, That is as simple as

    dmg_to_enemy = dice_rolls_combat(dwarf_class)
    

    although you can use any other variable name – this variable is unrelated to ones locally used elsewhere.