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.