Home > Net >  Global value doesn't change in python
Global value doesn't change in python

Time:07-17

The point is that the global value doesn't change to False (enemy_1_alive).

enemy_1_alive = True
enemy_1_reward = 2000
enemy_2_alive = True
enemy_2_reward = 3000
...
def mission(alive, reward):
    global enemy_1_alive
    if alive == True:
        alive = False
    elif alive == False:
        print('You already killed him!')
        time.sleep(2)

mission(enemy_1_alive, enemy_1_reward)
mission(enemy_2_alive, enemy_2_reward)
...

CodePudding user response:

If you want to use a global variable and want to modify it, because it is global, you don't need to pass it as a function argument. This should work for you.

enemy_1_alive = True
enemy_1_reward = 2000

def mission(reward):
    global enemy_1_alive
    if enemy_1_alive == True:
        enemy_1_alive = False
    elif enemy_1_alive == False:
        print('You already killed him!')
        time.sleep(2)

mission(enemy_1_reward)

Following your example you should do something like below, but it is useless code you write, this is because there is a better solution.

enemy_1_alive = True
enemy_1_reward = 2000

def mission(alive, reward):
    global enemy_1_alive
    if alive == True:
        enemy_1_alive = False
    elif alive == False:
        print('You already killed him!')
        time.sleep(2)

mission(enemy_1_alive, enemy_1_reward)

Edit: Okay so you should identify each enemy, you can use a a list dictionary and pass the index of an enemy.

enemies = [{"is_alive": False, "reward": 2000}, {"is_alive": True, "reward": 2000}]

def mission(enemy_index):
    global enemies
    enemy = enemies[enemy_index]
    if enemy['is_alive']:
        enemy['is_alive'] = False
    elif:
        print('You already killed him!')
        time.sleep(2)

mission(enemy_index) # For example 0 or 1
mission(enemy_index)

CodePudding user response:

try this :

enemy_1_alive = True
enemy_1_reward = 2000

def mission(alive, reward):
    global enemy_1_alive
    if alive == True:
        alive = False
    elif alive == False:
        print('You already killed him!')
        time.sleep(2)

mission(enemy_1_alive, enemy_1_reward)

CodePudding user response:

maybe because you never set enemy_1_alive = False

try to do :

enemy_1_alive = True
enemy_1_reward = 2000

def mission():
    global enemy_1_alive # this will import the global variable reference in the function
    if not enemy_1_alive : # is a better syntax for 'victim_1_alive == False'
        print('You already killed him!')
        time.sleep(2)

mission()
  • Related