Home > Enterprise >  How do I edit a global variable within a function
How do I edit a global variable within a function

Time:03-27

I'm new to python and I'm trying to make a small text based game I've listed the amount of health the player has and when I try to edit the variable within a function it doesn't change the global variable and when I try to use the global command to define it as a global variable it says the parameter is already a global variable and return also doesn't work?

import random
health = 100
dHealth = 1000

def attack(dHealth):
    attack = random.randint(5,50)
    dHealth = dHealth - attack
    print("You dealth", attack,"damage, the dragon has", dHealth,"health left!")
   
 
attack(dHealth)
print(dHealth)    

I wanted the variable to go from 1000 to a number between 995 to 950

CodePudding user response:

The best solution would be not to use it as a global variable. attack should take a value and return the updated value.

import random
health = 100
dHealth = 1000

def attack(monster, health):
    attack = random.randint(5,50)
    health = health - attack
    print("You dealt", attack,"damage, the ", monster, " has", health,"health left!")
    return health
   
 
dHealth = attack("dragon", dHealth)
print(dHealth)    

Since attack is, theoretically, no longer specific to the dragon's health, it takes an additional parameter to name the monster being attacked for the call to print.

CodePudding user response:

So you need to specify inside the function that it is the global variable you are trying to change. The code looks something like this:

import random
health = 100
dHealth = 1000

def attack(): # If you pass dHealth here, it only changes the local instance and not 
              # the global one
    global dHealth
    attack = random.randint(5,50)
    dHealth = dHealth - attack
    print("You dealth", attack,"damage, the dragon has", dHealth,"health left!")
   
 
attack()
print(dHealth)

But there is another way, and that is to return a value with the function and assign it to dHealth
Code:

import random
health = 100
dHealth = 1000

def attack(dHealth):
    attack = random.randint(5,50)
    dHealth = dHealth - attack
    print("You dealth", attack,"damage, the dragon has", dHealth,"health left!")
    return dHealth
   
 
dHealth = attack(dHealth) # Here, the returned value of dHealth after 
                          # reduction is assigned to the global variable
                          # so no need to use global variables
print(dHealth) 
  • Related