Home > other >  How to stop variables becoming local
How to stop variables becoming local

Time:06-25

I'm trying to create a function to verify if a move in a game is legal. At the top of my code, I declared the variable Valid.

p1 = [1,1]
p2 = [1,1]
turn = 1
move = 0
Valid = False

and later on, I call the function check_swap and right now, I am just returning that it is true (I will implement the checking later on):

  if move == 2:
    print("Swaping selected")
    print("you have "   str(p1[0]   p1[1])   " in total.")
    want_p1_hand_1 = input("How many do you want hand 1 to have?")
    want_p1_hand_2 = input("How many do you want hand 2 to have?")
    
    check_swap(p1, p2, turn, want_p1_hand_1, want_p1_hand_2)
    if Valid == True:
      p1[0] = want_p1_hand_1
      p1[1] = want_p1_hand_2
      print_game(p1, p2)
    else:
      print("That didn't work")
      
          
def check_swap(p1, p2, turn, want_p1_hand_1, want_p1_hand_2):
  Valid = True
  return Valid

Then, it defaults to the else statement and prints "That didn't work". At first I just had Valid = True, and it said that Valid was called but never used, even though it is. I searched Stackoverflow and adding the return Valid seemed like the right thing to do, but it didn't work.

CodePudding user response:

Valid = True in check_swap actually just creates a new local variable, separate from the global Valid.

Now, you could use the global statement, but a better way to write the code would be to assign the return value of check_swap to Valid.

Valid = check_swap(p1, p2, turn, want_p1_hand_1, want_p1_hand_2)

CodePudding user response:

To assign to global variables you'll need the global keyword. Here's an example ran in the Python REPL:

>>> valid = False
>>> 
>>> def not_using_global():
...     valid = True
...     print(valid)
...
>>> def using_global():
...     global valid
...     valid = True
...     print(valid)
...
>>>
>>> not_using_global()
True
>>> print (valid)
False
>>>
>>> using_global()
True
>>> print(valid)
True
  • Related