Forgive me if this question has been asked, but I can't seem to find it.
I've been trying to (re)create a game that involves two teams. I represent them using lists of the names of the players.
The problem that I'm facing is that from a module to another I don't keep my global variables.
This is the tree of my project :
Project_Folder
-- game.py
-- functions.py
-- variables.py
Inside the variables.py there is this :
player_list = []
team_1 = []
team_2 = []
And inside my functions.py :
import random
from variables import *
def init_teams():
global player_list
global team_1
global team_2
player_list = ["Player1", "Player2", "Player3", "Player4", "Player5"]
# stuff above is normaly done with inputs and loops, but i symplified it
for i in range(2):
team_2.append(player_list.pop(
random.randrange(len(player_list))))
team_1 = player_list.copy()
player_list += team_2
print(team_1)
And finally in the main.py :
from functions import *
init_players()
print("Team 1 : {}, Team 2 : {}, Players : {}".format(
team_1, team_2, player_list))
When I print the team_1
variable inside the function, I get the normal result but when I do it in the main.py I get an empty list. Same with the player_list
variable.
I've checked it with breakpoints using VS Code and seen that the team_1
is actually changing (from the normal list to an empty list) from the function to the main file, but I have no idea why it does that.
If you have an idea, please tell me what I missed, it would save me a lot of searching!
the global
keyword is working only in the used file. It can not be used to make value globally from another file.