-1

I am learning Python and I am having issues with gobal variable. I have defined the variables globally and then assigning them from the function using the global keyword. But still, when it runs the script, it is failing to assign the variable.

Looked at this solution, Using global variables in a function, and I don't know why his code is working and the same logic in mine is failing. Can't figure out and stuck in the small issue for hours.

def player_input():
    player_1_name = input('Please enter your name Player 1.')
    player_2_name = input('Please enter your name Player 2.')
    player_1_symbol='None'
    player_2_symbol=''
    allowed_symbol=['X','O']
    symbol_accepted = False

def get_symbol():
    global player_1_symbol
    player_1_symbol = input('Please enter your preferred symbol {}. It can be either X or O.   '.format(player_1_name))
    print('value of symbol after assignment: '+ player_1_symbol)

def validate_symbol():
    global symbol_accepted
    print('value of symbol when process started: '+ player_1_symbol)
    if player_1_symbol.upper() in allowed_symbol:
        print('it passed')
        symbol_accepted = True
    else:
        print('it came here, because it did not find the value of player_1_symbol')
        get_symbol()

while symbol_accepted == False:
    validate_symbol()

if player_1_symbol.upper() == 'O':
    player_2_symbol = 'X'
else:
    player_2_symbol = 'O'

print("{}, unfortunately you don't have choice. You have been assigned the symbol {}.".format(player_2_name,player_2_symbol))

The result I am trying to achieve is I want to assign player_1_symbol to global variable from get_symbol function. And the same goes for symbol_accepted. None of the variables are getting assigned. I am printing them but I can't just understand why it is not working. I saw a couple of videos on youtube and some articles.

I saw some other videos/articles on input validations, but once I started this I would like to learn what is wrong with it so I can work with global in the future.

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
Deep
  • 342
  • 3
  • 12
  • What do you mean they aren't getting assigned? Please provide a [mcve]. Note, this is simply a function definition, it is never called anywhere – juanpa.arrivillaga Aug 13 '20 at 19:45
  • Note, while `player_1_symbol` is global in `get_symbol`, it is local in `player_input` and non-local in `validate_symbol`. In any case, **you shouldn't be relying on global mutable state anyway** – juanpa.arrivillaga Aug 13 '20 at 19:46
  • So when I run the script, variable ```player_1_symbol``` first gets assigned as ```X``` but when it reaches to the point where it runs ```validate_symbol``` function it gets value as ```None```. I am expecting it to keep the value as ```X``` or ```O``` as per user input. – Deep Aug 13 '20 at 19:51
  • Side-note: defining the `player_1_symbol` and `player_2_symbol` in `player_input()` function is *really* of no use, since you are defining them again at run-time within `get_symbol()`. The 2nd comment explains it very well why one shouldn't depend on individual *global* variables (too much scope limitations/un-used memory in stack). – de_classified Aug 13 '20 at 19:54
  • 2
    As a programmer you should try very, *very*, **very** hard not to use globals. – quamrana Aug 13 '20 at 19:55
  • Sure, I removed global in my local and when I run I am back to square zero. So this is what it is happening. ```Please enter your name Player 1.A Please enter your name Player 2.B value of symbol when process started: None it came here, because it did not find the value of player_1_symbol Please enter your preffered symbol A. It can be either X or O. X **value of symbol after assignment**: X **value of symbol when process started**: None``` – Deep Aug 13 '20 at 19:57
  • I un-indented all the function definitions that you had nested inside `player_input()` because I assumed it was a question code formatting issue — but, it might be the cause of the issue if you really have them inside the first function like that… – martineau Aug 13 '20 at 20:00

1 Answers1

1

I created an array with player_symbols (player_1 is at 0 and player_2 is at 1) so the variables can be assigned correctly. I also fixed a bug where validate_symbol was repeating because symbol_accepted had the same error.

def player_input():
    player_1_name = input('Please enter your name Player 1.')
    player_2_name = input('Please enter your name Player 2.')
    player_symbols = ["", ""]
    allowed_symbol = ['X', 'O']
    symbol_accepted = False

    def get_symbol():
        player_symbols[0] = input(
            'Please enter your preferred symbol {}. It can be either X or O.   '.format(player_1_name))
        print('value of symbol after assignment: ' + player_symbols[0])

    def validate_symbol(symbol_accepted):
        print('value of symbol when process started: ' + player_symbols[0])
        if player_symbols[0].upper() in allowed_symbol:
            print('it passed')
            symbol_accepted = True
        else:
            print('it came here, because it did not find the value of player_1_symbol')
            get_symbol()
        return symbol_accepted

    while symbol_accepted == False:
        symbol_accepted = validate_symbol(symbol_accepted)

    if player_symbols[0].upper() == 'O':
        player_symbols[1] = 'X'
    else:
        player_symbols[1] = 'O'

    print("{}, unfortunately you don't have choice. You have been assigned the symbol {}.".format(player_2_name,
                                                                                                  player_symbols[1]))
player_input()
marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
jreiss1923
  • 464
  • 3
  • 11
  • so your solution works, but why only variable does not work instead of the list? – Deep Aug 13 '20 at 20:09
  • 1
    Having only the variable doesn't work because when you create player_1_symbol inside of a function python recognizes it as a new variable, not a global variable. As other commenters have said it isn't the best practice to use "global x" in your code, so I made a list containing your variables. – jreiss1923 Aug 13 '20 at 20:13