Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

Python Why isnt python seeing my variable as a global var?

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

Code:
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()
 
It means that you are trying to use the variable before it is created
Couple of things, You don't need global in this script. Any variable assigned will be available in the function unless changes within the function.
Also match is a python builtin, It's not recommended to use the built -ins. There are probably more errors, these are just what I noticed off hand.
 
Last edited:
It means that you are trying to use the variable before it is created
Couple of things, You don't need global in this script. Any variable assigned will be available in the function unless changes within the function.
Also match is a python builtin, It's not recommended to use the built -ins. There are probably more errors, these are just what I noticed off hand.
Well thanks for the response. Didn't realize that about match. Glad to know. In surprised Pycharm didn't tell me that. But on the other hand this doesn't really help me much. I do need to change the variable inside the function. How do I do that. On another forum somebody told me to use the global function inside the function and that did work for me. Is that what you would recommend? I'm trying to learn. If there are problems with my code please do tell me. Perhaps even rewrite it in a way that is more proper.
 
Here is a simple way to do it. The code can be optimized but, I wrote it to be easy to understand.

Python:
# Do the imports
from random import choice
import os

# Set some global variables
player_score = 0
computer_score = 0
ties = 0

def clear():
    ''' Function to clear the screen clutter '''
    os.system('cls' if os.name == 'nt' else 'clear')

def score(msg):
    ''' Function for displaying scores '''
    clear()
    print(f'Player: {player_score} | Computer: {computer_score} | Ties: {ties}')
    print(msg)

# Display the score at start
score(msg='Hello! Welcome to Rock, Paper Scissors.')

# Get the while loop started
while True:
    # Get player input
    play = input('Please type rock, paper, scissors and press enter.\n>> ')

    # Get a random choice for the computer
    pc = choice(['rock', 'paper', 'scissors'])

    # Check if player input is valid. If not go back to start
    if play not in ['rock', 'paper', 'scissors']:
        score('That is not a valid option. Please try again.')
        continue

    match play:
        # Match will check for player input then apply correct case
        # Here we also advance the correct player score if they win
        # We also have various message to be displayed depending on outcome
        case 'rock':
            if pc == 'scissors':
                msg = 'Rock smashes scissors - Player wins'
                player_score += 1
            elif pc == 'paper':
                msg = 'Paper covers rock - Computer wins'
                computer_score += 1
            else:
                msg = 'Tie Game'
                ties += 1
            score(msg)

        case 'paper':
            if pc == 'scissors':
                msg = 'Scissors cut paper - Computer wins.'
                computer_score += 1
            elif pc == 'rock':
                msg = 'Paper covers rock - Player wins'
                player_score += 1
            else:
                msg = 'Tie Game'
                ties += 1
            score(msg)

        case 'scissors':
            if pc == 'rock':
                msg = 'Rock smashes scissors - Computer wins'
                computer_score += 1
            elif pc == 'paper':
                msg = 'Scissors cut paper - Player wins.'
                player_score += 1
            else:
                msg = 'Tie Game'
                ties += 1
            score(msg)

        case _:
            print('unknown')
              
    # Ask if player wants to play again
    play_again = input('Play Again y/n: ').lower()
    if play_again == 'y':
        score(msg='')
    else:
        clear()
        score('Goodbye!')
        break
 
Back
Top Bottom