Search code examples
pythonglobal-variables

Unable to access what should be a global variable from function


from better_blackjack.preset_folder import build_deck

"""
This file is used to load all the things we need to run game.py (player_chips, deck, number of hands, bet amount)
"""




with open(r"C:\Hacks\python\programs\better_blackjack\Save_settings/chips.txt", "r") as file:
    file_data = file.read()
    if len(file_data) == 0:
        player_chips = 1000000  # This will get altered (live amount of chips)
    else:
        try:
            player_chips = int(file_data)
        except ValueError:
            print('File corrupted... restarting player chips ')
            player_chips = 1000000
print(player_chips)

def get_num_hands():
    try:
        num_hands = (int(input('How many hands would you like ? ')))
        get_bet_amount(num_hands)

    except ValueError:
        print('Use a valid number.')
        get_num_hands()


def get_bet_amount(num_hands):


    list_of_bets = []

    for i in range(1, num_hands+1):
        try:
            print('How much would you like to bet on hand', i, '   Balance', player_chips)
            bet_amount = int(input())
            list_of_bets.append(bet_amount)
            player_chips = player_chips - bet_amount
            if player_chips < 0:
                print('Bets exceed player balance... Restarting betting process')
                player_chips = int(file_data)
                get_bet_amount(num_hands)
                return None  # ends func

        except ValueError:
            print('Please use numbers only !... Restarting betting process')
            player_chips = int(file_data)
            get_bet_amount(num_hands)
            return None  # ends func


deck = build_deck.deck
get_num_hands()

I am getting the error 'player_chips' referenced before assignment on the following line - print('How much would you like to bet on hand', i, ' Balance', player_chips) However it is defined before we call any of our functions how could this be ?


Solution

  • If a variable is modified inside a function, it is a local variable, and has nothing to do with the global variable of the same name. Hence player_chips inside get_bet_amount has nothing to do with the variable of the same name used at top level.

    Add global player_chips inside your function to override this behavior.