0

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()

4 Answers 4

1

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()

Sign up to request clarification or add additional context in comments.

Comments

0

Your code rebinds jeuActuel rather than mutating it.

def nouveauJeu():
  global jeuActuel
   ...

Comments

0

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.

Comments

0

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().

1 Comment

Of course, this makes jeuActuel = {} completely pointless. And makes it rather odd to even define both names if they're always just references to the same dict.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.