Why is Python telling me variable is local not global?

Joined
Jul 20, 2023
Messages
56
Reaction score
2
Its telling me that user_score and comp_score is a local variable.
Im using Pycharm.

Exact Error: Unresolved reference 'user_score'
File "/home/mattyp77/PycharmProjects/RockPaperScissor/main.py", line 55, in battle
user_score += 1
UnboundLocalError: local variable 'user_score' referenced before assignment

Also what is this about?
Local variable 'user_selection' might be referenced before assignment

Python:
import time
import random
import os


def clear_screen():
    # Check if the operating system is Windows
    if os.name == 'nt':
        os.system('cls')  # For Windows
    else:
        os.system('clear')  # For other platforms like macOS and Linux


# MATCHES USERS MENU SELECTION TO ROCK, PAPER, OR SCISSOR
# THEN CALLS COMPUTER SELECTION FOR MATCH UP AND BATTLE
def match(user_selection):
    user_selection -= 1
    if user_selection == 3: exit()
    print('    YOU:\n', tool[user_selection], '\nVS', end='')
    for _ in range(4):
        print('.', end='')
        time.sleep(1)
    computer_play(user_selection)


def computer_play(user):
    comp = random.randint(0, 2)
    print('\n   COMPUTER: \n', tool[comp])
    battle(user, comp)


def battle(user, comp):
    # ROCK = 0 : PAPER = 1 : SCISSOR = 2
    print(user, ' ', comp)
    if user == comp:
        print("You are tied")
    elif user + 2 == comp or user - 1 == comp:
        print(f'You WIN. {rck_ppr_scssr[user].upper()} beats {rck_ppr_scssr[comp].upper()}')
        user_score += 1
    else:
        print(f'Computer WINS. {rck_ppr_scssr[comp].upper()} beats {rck_ppr_scssr[user].upper()}')
        computer_score += 1
    print(f'Score: \n You: {user_score} \n Computer: {computer_score}')


def main_menu():
    while True:
        try:
            clear_screen()
            print(' ' * 40, 'Rock Paper Scissor\n')
            print('Enter your selection: \n1. Rock \n2. Paper \n3. Scissor\n4. Quit \n')

            user_selection = int(input(': '))
            if user_selection not in range(1, 5):
                clear_screen()
                print('Select a number between 1 and 4')
                input('Press ENTER to continue ')
                continue
            break
        except:
            clear_screen()
            print('Please enter only digits')
            input('Press ENTER to continue ')
            continue
    match(user_selection)


# ______________MAIN BODY _________________
go_again = 'y'
rck_ppr_scssr = ('rock', 'paper', 'scissor')
tool = ['ROCK', 'PAPER', 'SCISSOR']
global user_score; user_score = 0
global computer_score; computer_score = 0

# THIS IS FOR FILES I CREATED WITH ASCII ART. FOR SIMPLICITY I JUST CREATED THE
# tool [] LIST IN ITS PLACE
#for x in rck_ppr_scssr:
#    f = open(f'{x}.x', 'r')
#    tool.append(f.read())
#    f.close()

while go_again in ['y', 'yes']:
    main_menu()
    go_again = input('Keep playing? (Y/N): ').lower()
 
Last edited:
Joined
Jul 4, 2023
Messages
507
Reaction score
63
Use the global keyword inside function (def)

[ on-line ]
Python:
def battle(user, comp):
    global user_score, computer_score

  1. When You Really Need Global Variables:
    There are situations where you need multiple functions to access and/or modify the same global variable. For example, a global variable might store configuration settings or data that is used in different parts of the program.

  2. Updating Global Variables Inside Functions:
    If you need to change the value of a global variable within a function, use global to indicate that you are working with the global version of the variable.

  3. Preserving a Reference to an Object:
    If you are working with mutable objects such as lists or dictionaries and want to modify their contents within a function, you can use global to maintain a reference to the global object.
 
Joined
Jul 20, 2023
Messages
56
Reaction score
2
Use the global keyword inside function (def)

[ on-line ]
Python:
def battle(user, comp):
    global user_score, computer_score

  1. When You Really Need Global Variables:
    There are situations where you need multiple functions to access and/or modify the same global variable. For example, a global variable might store configuration settings or data that is used in different parts of the program.

  2. Updating Global Variables Inside Functions:
    If you need to change the value of a global variable within a function, use global to indicate that you are working with the global version of the variable.

  3. Preserving a Reference to an Object:
    If you are working with mutable objects such as lists or dictionaries and want to modify their contents within a function, you can use global to maintain a reference to the global object.
Cool thanks. What do you think of the code? Any criticism?
 
Joined
Sep 21, 2022
Messages
189
Reaction score
26
"What do you think of the code? Any criticism?"

Too long.

A simple game only needs a simple program.

I'd guess 25 lines.

Just my opinion.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,056
Messages
2,570,443
Members
47,089
Latest member
Bobby2025b

Latest Threads

Top