Reputation: 11
Is there a reason why this doesn't copy "jeuOriginal" on "jeuActuel"?
Does not work on Python 2.7 and on Python 3
jeuOriginal = {}
jeuActuel = {}
def nouveauJeu():
nombreCases = int(raw_input())
chiffre = 0
for i in range(1, nombreCases + 1):
for j in range(1, nombreCases + 1):
jeuOriginal[(i, j)] = chiffre
chiffre = chiffre + 1
jeuActuel = jeuOriginal
def ordre():
nouveauJeu()
print(jeuOriginal)
print(jeuActuel)
ordre()
Upvotes: 0
Views: 58
Reputation: 2403
You don't need to rely on globals for this, because dictionaries are mutable, all you need to do is move the one line (jeuActuel = jeuOriginal) to outside the function:
jeuOriginal = {}
jeuActuel = jeuOriginal
def nouveauJeu():
nombreCases = int(raw_input())
chiffre = 0
for i in range(1, nombreCases + 1):
for j in range(1, nombreCases + 1):
jeuOriginal[(i, j)] = chiffre
chiffre = chiffre + 1
def ordre():
nouveauJeu()
print(jeuOriginal)
print(jeuActuel)
ordre()
You also don't need to declare jeuActuel as an empty dictionary first. By doing this, both the names jeuOriginal and jeuActuel both point to the same dictionary, which is mutated (changed) in the function nouveauJeu().
Upvotes: 0
Reputation: 133
The jeuActuel variable defined at the top is not a global variable until you define it using the global variable (either at the top or inside the method where you are assigning)
The problem you are facing is because a local variable jeuActuel is also getting created inside nouveauJeu().
local value of jeuActuel (inside nouveauJeu) : jeuOriginal
value of jeuActuel in the outer scope : {}
So while printing, the program accesses the outer scope value and thus prints {}
What you can do (as mentioned by Ignacio) is declare jeuActuel as global inside nouveauJeu()
Upvotes: 1
Reputation: 1573
jeuOriginal
is only defined in your inner for loop. To get your code running define jeuOriginal = [[0] * nombreCases] * nombreCases
in front of your loop. Furthermore, you cannot request a variable from another function in Python. To do so you will need to create a class or use global with an outside definition of your important variables.
Upvotes: 0
Reputation: 798686
Your code rebinds jeuActuel
rather than mutating it.
def nouveauJeu():
global jeuActuel
...
Upvotes: 0